Download audit report
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 Type | Security Review |
| Initial Report | October 31, 2023 |
| Final Report | November 2, 2023 |
| Methods | Manual Review, Automated Analysis, Tests |
| Repository | AVNU Contracts V2 |
| Commit Hash | 6845406ad6 |
| Documentation | README.md |
| Documentation Assessment | Medium |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | src/interfaces.cairo | 2 | 0 | 0.0% | 0 | 2 |
| 2 | src/exchange.cairo | 327 | 38 | 11.6% | 49 | 414 |
| 3 | src/models.cairo | 8 | 1 | 12.5% | 1 | 10 |
| 4 | src/adapters.cairo | 19 | 1 | 5.3% | 2 | 22 |
| 5 | src/lib.cairo | 6 | 1 | 16.7% | 1 | 8 |
| 6 | src/math.cairo | 2 | 0 | 0.0% | 0 | 2 |
| 7 | src/math/sqrt_ratio.cairo | 24 | 0 | 0.0% | 0 | 24 |
| 8 | src/math/muldiv.cairo | 35 | 5 | 14.3% | 8 | 48 |
| 9 | src/adapters/ekubo_adapter.cairo | 156 | 27 | 17.3% | 23 | 206 |
| 10 | src/adapters/myswapv2_adapter.cairo | 57 | 11 | 19.3% | 9 | 77 |
| 11 | src/adapters/sithswap_adapter.cairo | 54 | 7 | 13.0% | 8 | 69 |
| 12 | src/adapters/jediswap_adapter.cairo | 42 | 6 | 14.3% | 7 | 55 |
| 13 | src/adapters/tenkswap_adapter.cairo | 48 | 7 | 14.6% | 8 | 63 |
| 14 | src/adapters/myswap_adapter.cairo | 37 | 4 | 10.8% | 4 | 45 |
| 15 | src/interfaces/locker.cairo | 6 | 2 | 33.3% | 1 | 9 |
| 16 | src/interfaces/erc20.cairo | 7 | 1 | 14.3% | 1 | 9 |
| Total | 830 | 111 | 13.4% | 122 | 1063 |
| # | Finding | Severity | Update |
| 1 | Missing validation of token addresses in routes data | Medium | Fixed |
| 2 | Percentages in routes data may cause residual tokens | Medium | Fixed |
| 3 | Not using a two-step process for transferring ownership | Low | Mitigated |
| 4 | Unnecessary on-chain deadline calculation | Info | Fixed |
| 5 | Lack of input validation in multi_route_swap(...) | Best Practices | Fixed |
| 6 | Missing boundaries for fees | Best Practices | Fixed |
| 7 | Missing check for ranges | Best Practices | Acknowledged |
| 8 | Missing validation for Route.percentage | Best Practices | Fixed |
| 9 | Unused parameter token_to_amount | Best Practices | Acknowledged |
| 10 | Unused variable myswapv2_adapter.exact_input | Best Practices | Fixed |
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.
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.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
| File | Fix commit | Type | Status |
exchange.cairo | 01cbbd1 | Medium | Fixed |
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:
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;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.
| File | Fix commit | Type | Status |
exchange.cairo | 01cbbd1 | Medium | Fixed |
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.
| File | Fix commit | Type | Status |
exchange.cairo | — | Low | Mitigated |
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.
| File | Fix commit | Type | Status |
sithswap_adapter.cairotenkswap_adapter.cairojediswap_adapter.cairo | 08673de | Info | Fixed |
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.
multi_route_swap(...)| File | Fix commit | Type | Status |
exchange.cairo | 5bc4faf | Best Practices | Fixed |
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.
| File | Fix commit | Type | Status |
exchange.cairo | 21eb34d | Best Practices | Fixed |
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.
| File | Fix commit | Type | Status |
src/* | — | Best Practices | Acknowledged |
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.
Route.percentage| File | Fix commit | Type | Status |
exchange.cairo | c13a5ac | Best Practices | Fixed |
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.
token_to_amount| File | Fix commit | Type | Status |
exchange.cairo | — | Best Practices | Acknowledged |
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.
myswapv2_adapter.exact_input| File | Fix commit | Type | Status |
myswapv2_adapter.cairo | c16940f | Best Practices | Fixed |
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.
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:
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.
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.
| 41Tests passed | 0Failed |
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.
The Leading Engineers of Blockchain Infrastructure