AVNU
DEX Aggregator

AVNU finds the best trade route across Starknet AMMs like Ekubo, JediSwap and mySwap. We reviewed the Cairo contracts that execute those routes.
report id
0141
category
DeFi & Yield
language
Cairo
final report
November 2, 2023
lines of code
830
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind for the AVNU protocol. AVNU provides a DEX aggregator that scans and combines liquidity from various AMMs to find the best trading route, minimizing slippage and optimizing trade execution. By aggregating multiple liquidity sources, AVNU ensures that users have access to the most competitive prices available in the market. The protocol has integrations with well-recognized AMM’s, such as ekubo, sithswap, jediswap, 10kswap, and Braavos mySwap.

The audited code comprises 830 lines of Cairo code. During the audit, we observed that the code lacks validation for some variables within valid ranges. Although we have not currently identified any specific attack vectors associated with these missing validations, it is prudent to ensure that all variables consistently conform to valid ranges. This practice will significantly reduce the likelihood of encountering instances where invariants break.

Consequently, we recommend that the AVNU team undertake a comprehensive examination of the entire codebase to confirm that each function rigorously tests preconditions and postconditions. Moreover, it is of utmost importance to verify that each variable undergoes meticulous scrutiny to guarantee compliance with valid ranges. Specifically, percentages should not exceed 100%, fees should be subject to appropriate restrictions, addresses must not be null, and amounts should not be zero. Furthermore, routes should always contain valid data, and it is imperative to impose a maximum length on routes to prevent arbitrary sizes, which could potentially introduce vulnerabilities and opportunities for exploitation.

It is highly advisable to ensure that all variables remain within acceptable ranges across all AVNU contracts. In exploiting smart contracts, attackers seek to manipulate the system into an invalid state by compromising one or more invariants, leaving the system vulnerable. To mitigate the risk of such attacks, it is critical to maintain the system in a continuously valid state. This can be achieved through thorough validation of preconditions before executing functions and conducting comprehensive checks on post-conditions after execution. We strongly recommend the application of these principles to every function and variable within AVNU.

The audit was performed using: (a) manual analysis of the codebase and (b) simulation of the smart contracts.

Audit assessment
Audit TypeSecurity Review
Initial ReportOctober 31, 2023
Final ReportNovember 2, 2023
MethodsManual Review, Automated Analysis, Tests
RepositoryAVNU Contracts V2
Commit Hash6845406ad6
DocumentationREADME.md
Documentation AssessmentMedium
Test Suite AssessmentHigh
Total findings
10
Fixed
7
Acknowledged
2
Mitigated
1
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium2
  • Low1
  • Informational1
  • Best Practices6

4

System Overview

AVNU allows for multi-route swaps using a set of well-established AMMs (Automated Market Makers). Each AMM can be plugged into AVNU using the abstraction called adaptor. The adaptor defines the communication interface between external AMMs and AVNU. The interface is reproduced below.

#[starknet::interface]
trait ISwapAdapter<TContractState> {
fn swap(
self: @TContractState,
exchange_address: ContractAddress,
token_from_address: ContractAddress,
token_from_amount: u256,
token_to_address: ContractAddress,
token_to_min_amount: u256,
to: ContractAddress,
additional_swap_params: Array<felt252>,
);
}

The core contract is exchange.cairo. The contract uses the following storage variables for fee data, owner address, and adapters’ class hashes.

#[storage]
struct Storage {
Ownable_owner: ContractAddress,
AdapterClassHash: LegacyMap<ContractAddress, ClassHash>,
fees_active: bool,
fees_bps_0: u128,
fees_bps_1: u128,
fees_recipient: ContractAddress,
}

The contract emits events for swaps and ownership transfers.

#[event]
#[derive(starknet::Event, Drop, PartialEq)]
enum Event {
Swap: Swap,
OwnershipTransferred: OwnershipTransferred,
}

The struct Swap is used to emit events after the swap is completed.

#[derive(Drop, starknet::Event, PartialEq)]
struct Swap {
taker_address: ContractAddress,
sell_address: ContractAddress,
sell_amount: u256,
buy_address: ContractAddress,
buy_amount: u256,
beneficiary: ContractAddress,
}

Ownership transfers are recorded using the following structure.

#[derive(starknet::Event, Drop, PartialEq)]
struct OwnershipTransferred {
previous_owner: ContractAddress,
new_owner: ContractAddress,
}

The constructor sets the owner of the contract and the fee recipient.

#[constructor]
fn constructor(
ref self: ContractState, owner: ContractAddress, fee_recipient: ContractAddress
) {
// Set owner & fee collector address
self._transfer_ownership(owner);
self.fees_recipient.write(fee_recipient)
}

The contract also has a set of admin and operational functions defined in the trait IExchange.

trait IExchange<TContractState> {
fn get_owner(self: @TContractState) -> ContractAddress;
fn transfer_ownership(ref self: TContractState, new_owner: ContractAddress) -> bool;
fn upgrade_class(ref self: TContractState, new_class_hash: ClassHash) -> bool;
fn get_adapter_class_hash(
self: @TContractState, exchange_address: ContractAddress
) -> ClassHash;
fn set_adapter_class_hash(
ref self: TContractState, exchange_address: ContractAddress, adapter_class_hash: ClassHash
) -> bool;
fn get_fees_active(self: @TContractState) -> bool;
fn set_fees_active(ref self: TContractState, active: bool) -> bool;
fn get_fees_recipient(self: @TContractState) -> ContractAddress;
fn set_fees_recipient(ref self: TContractState, recipient: ContractAddress) -> bool;
fn get_fees_bps_0(self: @TContractState) -> u128;
fn set_fees_bps_0(ref self: TContractState, bps: u128) -> bool;
fn get_fees_bps_1(self: @TContractState) -> u128;
fn set_fees_bps_1(ref self: TContractState, bps: u128) -> bool;
fn multi_route_swap(
ref self: TContractState,
token_from_address: ContractAddress,
token_from_amount: u256,
token_to_address: ContractAddress,
token_to_amount: u256,
token_to_min_amount: u256,
beneficiary: ContractAddress,
integrator_fee_amount_bps: u128,
integrator_fee_recipient: ContractAddress,
routes: Array<Route>,
) -> bool;
}

The function multi_route_swap(...) implements the core use case. It receives the address and amount of the source token, the address and minimal amount required from the destination token. It can define another address to receive the destination tokens (i.e., the beneficiary). However, the current implementation requires the beneficiary to be the caller’s address, as shown below.

// In the future, the beneficiary may not be the caller
// Check if beneficiary == caller_address
assert(beneficiary == caller_address, 'Beneficiary is not the caller');

The function multi_route_swap also defines fee parameters and the route for the trade. The route specifies the AMMs that will be used to perform the swap, including the percentage of tokens to be traded using each AMM.

4.1 Assumptions

During the course of our review for AVNU, we focused primarily on the smart contract code and operational logic specific to the aggregator itself. We did not review the smart contracts of the protocols that the aggregator integrates with. The following assumptions were made with regard to the integrated protocols:

Correct integration assumption

We assume the integration between AVNU and the integrated protocols is implemented correctly. This includes, but is not limited to, data retrieval, transaction forwarding, fee calculations, and any other interactions between the aggregator and the integrated protocols.

Reliability of integrated protocols

We assume the integrated protocols are secure, reliable, and function as intended. Any vulnerabilities or malfunctions within those protocols are beyond the scope of our audit and could have potential implications for the aggregator.

By clarifying these assumptions, we intend to provide a clear delineation of our assessment’s scope and to ensure that stakeholders are aware of the boundaries of our review.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Missing validation of token addresses in routes data

FileFix commitTypeStatus
exchange.cairo01cbbd1MediumFixed

The routes array, within the multi_route_swap(...) function, holds the data required for token swaps across multiple pools using the apply_routes(...) function. However, it is important to note that there is no guarantee that the address of the first swapped token matches the token_from_address passed into the before_swap(...) function. Likewise, the address of the last token swapped does not necessarily align with the token_to_address used in the after_swap(...) function. This lack of alignment potentially introduces the possibility of disparate addresses, giving rise to the following scenarios:

  • Inaccurate Data in the Swap Event Emitted: Consider a scenario where the routes consist of tokens A and B designated for swapping. A user invokes multi_route_swap(...) and provides the address of token C as the token_from_address (with token_to_amount=0). Simultaneously, the user correctly forwards the required amount of tokens A directly to the Exchange contract. This configuration allows for the accurate execution of swaps defined within the routes. However, it is noteworthy that the Swap event emitted in this process will contain incorrect data. Such discrepancies have the potential to impact monitoring activities and the user interface;
  • Reduced Fee for Complex Routing: Consider a scenario where the routes define an intricate token swap from A to B involving multiple pools. A user initiates the multi_route_swap(...) function, providing the specified routes and designating token C as the token_to_address. In this sequence, the entire quantity of token B that was intended to be swapped remains within the Exchange contract, and no token C is transferred to the caller. Subsequently, in a separate call, the user invokes multi_route_swap(...) with an empty routing while specifying the token B address as the token_to_address. In this context, the current length of the routes array does not exceed one, leading to the interpretation that the routing is not complex. Consequently, a reduced fee, denoted as fees_bps_0, is collected;

Recommendation

It is advisable to incorporate checks within the system to verify that the initial token address involved in the first swap corresponds to the token_from_address. Likewise, it is essential to ensure that the token acquired through the final swap precisely matches the token_to_address. Additionally, the function after_swap(...) must check if all the tokens defined in the route.token_from and route.token_to are not left in the Exchange contract, except the token_to_address.

Resolution

Fixed in commit 01cbbd19278cdd956a799aea8fc7d62539225da3.

6.2 Percentages in routes data may cause residual tokens

FileFix commitTypeStatus
exchange.cairo01cbbd1MediumFixed

The function apply_routes(...) has the capability to perform a partial swap of the originally deposited quantity, as indicated by the variable token_from_amount, to satisfy the condition of receiving a minimum number of tokens, as specified by the value of the variable token_to_min_amount. This could potentially allow the Exchange contract to retain some tokens in its possession, not executing the swap of all tokens deposited by the caller_address. The code with audit comments is reproduced below.

fn after_swap(...) {
let token_to = IERC20Dispatcher { contract_address: token_to_address };
let received_token_to = token_to.balanceOf(contract_address);
let token_to_final_amount = self
.collect_fees(
token_to,
received_token_to,
integrator_fee_amount_bps,
integrator_fee_recipient,
route_len
);

assert(token_to_min_amount <= token_to_final_amount, 'Insufficient tokens received');

/////////////////////////////////////////////////////////////////////
// @audit Missing validation: Not checking if "route.token_from"
// and "route.token_to" have been completely swapped.
/////////////////////////////////////////////////////////////////////

token_to.transfer(beneficiary, token_to_final_amount);
...
}

Recommendation

The function after_swap(...) must check if all the tokens defined in the route.token_from and route.token_to are not left in the Exchange contract, except the token_to_address.

Resolution

Fixed in commit 01cbbd19278cdd956a799aea8fc7d62539225da3.

6.3 Not using a two-step process for transferring ownership

FileFix commitTypeStatus
exchange.cairo—LowMitigated

Currently, the ownership is directly transferred by calling transfer_ownership(...) by the protocol owner. However, this is error-prone, and accidentally transferring ownership to the incorrect address may result in loss of ownership over the protocol.

Recommendation

We strongly advise the implementation of a two-step ownership transfer mechanism that would facilitate the proposal of a new owner and the subsequent acceptance of ownership by the designated address.

Resolution

The owner role will be held by a multi-sig account. Every action done from it will be carefully reviewed before being submitted.

6.4 Unnecessary on-chain deadline calculation

In Automated Market Makers (AMMs), deadlines are commonly employed to prevent situations where a swap transaction lingers excessively in the mempool, potentially causing price fluctuations from when the transaction is dispatched. Nevertheless, on-chain computation of the deadline, which occurs when the transaction is executed, is superfluous. This is because the current block timestamp is utilized in the calculation, guaranteeing the perpetuity of the deadline’s validity. The code with audit comments is reproduced below.

// Init deadline
let block_timestamp = get_block_timestamp();
// @audit No meaning when calculating deadline on-chain
let deadline = block_timestamp + 1000;

Recommendation

We recommend computing the deadline off-chain and passing it to each external swap function. Or if the deadline is intentionally missed, simply pass the current block timestamp.

Resolution

Fixed in commit 08673de6535366ea532b3e69be16f8e3edfc20da.

6.5 Lack of input validation in multi_route_swap(...)

FileFix commitTypeStatus
exchange.cairo5bc4fafBest PracticesFixed

The function multi_route_swap(...) lacks a verification for the condition where token_from_amount is greater than zero. It can save gas when the user inputs a wrong value.

fn multi_route_swap(...) -> bool {
...
//////////////////////////////////////////////////////////////////////////
// @audit "token_from_amount" must be greater than zero
//////////////////////////////////////////////////////////////////////////
...
}

Recommendation

Revert the transaction if token_from_amount is zero.

fn multi_route_swap(...)
...
+ assert(token_from_amount > 0, 'Amount must be greater than zero');
...
}

Resolution

Fixed in commit 5bc4fafce484b8a58cbd8c6bbaafaac37fcc62d5.

6.6 Missing boundaries for fees

FileFix commitTypeStatus
exchange.cairo21eb34dBest PracticesFixed

The protocol does not account for valid fee ranges within the functions set_fees_bps_0(...) and set_fees_bps_1(...). Furthermore, there is an absence of restrictions on the ability to set fees by integrators.

Recommendation

We recommend defining valid ranges for fees.

Resolution

Fixed in commit 21eb34dc68e4745afce5ba47e7c8b0094239b7ac.

6.7 Missing check for ranges

FileFix commitTypeStatus
src/*—Best PracticesAcknowledged

The current codebase does not validate all variables for valid ranges. Even though there are no specific issues observed due to these missing validations, it is recommended to ensure all variables adhere to valid ranges, minimizing the risk of broken invariants.

Recommendation

Consider a thorough examination of the entire codebase to ensure each function checks proper preconditions and postconditions rigorously. Confirmation of each variable’s compliance with valid ranges is crucial. Specifically, percentages should not exceed 100%, fees should not be unrestricted, addresses and amounts should not be zero, and routes should never be empty or allowed to have arbitrary sizes. These principles should be applied to every function and variable within AVNU.

6.8 Missing validation for Route.percentage

FileFix commitTypeStatus
exchange.cairoc13a5acBest PracticesFixed

The function fn apply_routes(...) lacks validation for ensuring that route.percent.into() is less than or equal to 100. While we currently do not observe a specific attack vector associated with this vulnerability, it is advisable to take measures to ensure that all variables adhere to valid ranges. This will help minimize the chances of encountering broken invariants. Below, you will find the function with audit comments included for reference.

fn apply_routes(
ref self: ContractState, mut routes: Array<Route>, contract_address: ContractAddress
) {
...
/////////////////////////////////////////////////////////////
// @audit "route.percent" must be less or equal to 100
// @audit "route.percent" must be greater than or equal to 0
/////////////////////////////////////////////////////////////
let (token_from_amount, overflows) = muldiv(
token_from_balance, route.percent.into(), 100_u256, false
);
assert(overflows == false, 'Overflow: Invalid percent');
...
}

Recommendation

Ensure that Route.percentage is less than or equal to 100% and greater than 0%. Do not allow Route.percentage equals 0%.

Resolution

Fixed in commit c13a5acdfe440f1de4195665ac9c728c92d41527.

6.9 Unused parameter token_to_amount

FileFix commitTypeStatus
exchange.cairo—Best PracticesAcknowledged

The function multi_route_swap(...) does not use the input parameter token_to_amount. Instead, the logic relies on the token_to_min_amount.

Recommendation

Evaluate if the parameter token_to_amount is really required. It seems redundant with the parameter token_to_min_amount.

6.10 Unused variable myswapv2_adapter.exact_input

FileFix commitTypeStatus
myswapv2_adapter.cairoc16940fBest PracticesFixed

The variable exact_input is set in the myswapv2_adapter::swap(...) but not used.

Recommendation

The AVNU team must decide if this variable should be used or removed from the code.

Resolution

Fixed in commit c16940f2775b81e17faab8027de4596dc1d800c1.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

AVNU has sufficient documentation on the website and inline comments. Moreover, the client provided additional detailed documentation for the audit team. During the audit process, the audit team remained in constant communication with the client.

Test suite
41Tests passed0Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.