Download audit report
This document outlines the security review conducted by Nethermind for the LayerAkira on-chain settlement layer. LayerAkira is a hybrid central limit orderbook protocol where users can submit signed orders to an off-chain orderbook which will match and execute trades through the LayerAkira Cairo contracts. Liquidity can be sourced from orders submitted by users, or routers, which are entities that allow funds to be sourced from other means outside of the LayerAkira ecosystem.
The audited code comprises 3210 lines of code. The LayerAkira team has provided comprehensive documentation explaining the behavior of protocol and the reviewed smart contracts. Aside from the provided documentation, the LayerAkira and Nethermind Security teams have communicated to clarify any remaining questions about the expected behavior of the protocol.
The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contract. Along with this document, we report 12 points of attention, where one is classified as Medium, three are classified as Low, four are classified as Info and four are classified as Best Practices.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | June 21, 2024 |
| Response from Client | June 21, 2024 |
| Final Report | June 28, 2024 |
| Repository | LayerAkira/kurosawa_akira |
| Commit (Audit) | f1cb9acbd3 |
| Commit (Final) | 94e206a705 |
| Documentation Assessment | High |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | src/ILayerAkira.cairo | 126 | 16 | 12.7% | 49 | 191 |
| 2 | src/FundsTraits.cairo | 16 | 11 | 68.8% | 4 | 31 |
| 3 | src/lib.cairo | 15 | 0 | 0.0% | 0 | 15 |
| 4 | src/WithdrawComponent.cairo | 188 | 21 | 11.2% | 47 | 256 |
| 5 | src/NonceComponent.cairo | 139 | 2 | 1.4% | 19 | 160 |
| 6 | src/EcosystemTradeComponent.cairo | 888 | 26 | 2.9% | 70 | 984 |
| 7 | src/ExchangeBalanceComponent.cairo | 283 | 3 | 1.1% | 30 | 316 |
| 8 | src/SignerComponent.cairo | 90 | 7 | 7.8% | 13 | 110 |
| 9 | src/DepositComponent.cairo | 77 | 3 | 3.9% | 12 | 92 |
| 10 | src/RouterComponent.cairo | 332 | 38 | 11.4% | 45 | 415 |
| 11 | src/LayerAkira.cairo | 457 | 2 | 0.4% | 42 | 501 |
| 12 | src/Order.cairo | 300 | 7 | 2.3% | 31 | 338 |
| 13 | src/signature.cairo | 3 | 0 | 0.0% | 0 | 3 |
| 14 | src/utils.cairo | 4 | 0 | 0.0% | 0 | 4 |
| 15 | src/utils/erc20.cairo | 21 | 2 | 9.5% | 1 | 24 |
| 16 | src/utils/common.cairo | 17 | 0 | 0.0% | 2 | 19 |
| 17 | src/utils/account.cairo | 17 | 0 | 0.0% | 1 | 18 |
| 18 | src/utils/SlowModeLogic.cairo | 6 | 0 | 0.0% | 1 | 7 |
| 19 | src/signature/V0OffchainMessage.cairo | 55 | 3 | 5.5% | 6 | 64 |
| 20 | src/signature/AkiraV0OffchainMessage.cairo | 158 | 12 | 7.6% | 16 | 186 |
| 21 | src/signature/IOffchainMessage.cairo | 18 | 0 | 0.0% | 4 | 22 |
| Total | 3210 | 153 | 4.8% | 393 | 3756 |
| # | Finding | Severity | Update |
| 1 | User may not be able to apply on-chain withdrawals | Medium | Fixed |
| 2 | Receiver address for withdrawals is never checked | Low | Fixed |
| 3 | Router punishment can be abused to extract unclaimed router fees | Low | Fixed |
| 4 | fee_recipient address can be set to zero address | Low | Fixed |
| 5 | Missing validation could lead to deny new exchange version | Info | Fixed |
| 6 | Good After Time (GAT) orders can be filled before their valid date | Info | Mitigated |
| 7 | Tautology in the _transfer function | Info | Fixed |
| 8 | The _do_part_external_taker_validate function validates taker order’s nonce with itself | Info | Fixed |
| 9 | Inconsistency in error message | Best Practices | Fixed |
| 10 | bind_to_signer does not check signer address | Best Practices | Fixed |
| 11 | Function/variable/comment corrections | Best Practices | Fixed |
| 12 | Redundant checking in the function do_maker_checks | Best Practices | Fixed |
LayerAkira Contract: Fig. 2 presents the component diagram for the LayerAkira on-chain settlement layer. The LayerAkira block (in yellow) represents the contract LayerAkira where all other components (in blue color) are imported. Admin only functionality such as the managment of versions, routers, whitelisted invokers, and the fee recipient is handled here. All other relevant functions from the components illustrated on the diagram are publicly exposed to whitelisted invokers and users through this contract.
Functions and Structs: There are several cairo files that contain structs and functions used by components. For example, the Order consists of several structs to organize data related to orders and functions to validate taker and maker orders.
DepositComponent: Allows users to directly deposit to the contract, where their funds can be used to create and sign orders to be submitted to the orderbook. This component relies on the ExchangeBalanceComponent to update balances upon a successful deposit.
EcosystemTradeComponent: Contains the majority of logic related to validation and settlement of matched orders. Two order match functions apply_ecosystem_trades and apply_single_taker are exposed by the LayerAkira contract allowing whitelisted invokers to execute orders. The punishment mechanism for routers which sign trades that are unexecutable is also handled within this component.
ExchangeBalanceComponent: Tracks user deposits and (partial) router balances as deposits and withdrawals occur. Additional functions exist to support gas payments to compensate for whitelisted invoker execution costs as well as balance adjustments after orders have been matched and executed.
NonceComponent: Handles nonces for users, with an public function allowing users to increase their nonce. These nonces are part of the order data, and are validated during execution to ensure that the nonce is not lower than the current. This allows users to invalidate all their existing orders if necessary.
RouterComponent: Logic for management of routers, which connects LayerAkira to external sources of liquidity. It contains functions for router registration, deposits, withdrawals and signer binding. Routers can also be de-registered with a delay, where they must first request and then apply.
SignerComponent: Contains logic for verifying that signatures are valid, as well as allowing traders to bind a signer address to their own address, meaning that signatures can be verified with a different address from the one that recieves funds.
WithdrawComponent: Mechanism for allowing users to withdraw funds in two different ways. The first approach is to have a whitelisted invoker execute the withdrawal. This will occur immediately and funds are sent to the recipient with no time delay. A user is also able to initiate a withdrawal of their funds at any time, with a certain delay. This delay gives the off-chain orderbook a grace period to react to any existing orders that may rely on the liquidity about to be removed.
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 |
src/WithdrawComponent.cairo | — | Medium | Fixed |
The user can apply off-chain and on-chain withdrawals. When users call the request_onchain_withdraw function, it creates a pending withdrawal request for a particular token. Later, they need to invoke the apply_onchain_withdraw function to complete the ongoing request. On the other hand, they can withdraw by validating their signature. This issue emerges according to the order of calls, for example:
1. Alice calls request_onchain_withdraw to request an on-chain withdrawal of 100 A. Then, the function creates a pending request in pending_reqs for token A.
let key = (withdraw.token, withdraw.maker);
self.pending_reqs.write(key, (SlowModeDelay {block:get_block_number(), ts: get_block_timestamp()}, withdraw));2. Alice decides not to wait the minimum period to apply the on-chain withdrawal through the apply_onchain_withdraw and executes the off-chain withdrawal of 100 tokens A by validating her signature.
3. Later, she wants to execute an on-chain withdrawal of 50 for A. She needs to create a new request because the pending one is with 100 tokens A. The request_onchain_withdraw function checks whether the previous pending request is completed, thus reverting the transaction.
fn request_onchain_withdraw(ref self: ComponentState<TContractState>, withdraw: Withdraw) {
// ...
let (pending_ts, w_prev): (SlowModeDelay, Withdraw) = self.pending_reqs.read(key);
let w_hash = withdraw.get_message_hash(withdraw.maker);
assert!(w_prev != withdraw, "ALREADY_REQUESTED: withdraw for this token already requested");
// @audit it will revert when checking if the request is completed.
// The hash for w_prev can be different from withdraw
// because we have several attributes in the
// Withdraw struct. Particularly, the values in the gas_fee
// struct tend to change
assert!(w_prev.amount == 0 || self.completed_reqs.read(w_prev.get_message_hash(w_prev.maker)), "NOT_YET_COMPLETED_PREV: previous withdraw has not been completed yet");
// ...
}Then, Alice is forced to withdraw 100 tokens A (that she has already withdrawn) if she wants to continue to use the on-chain withdraw method. Otherwise, she will be able to execute only off-chain withdrawals. We can extend this example to millions of tokens A where the user may not be able/interested to complete the pending request.
Recommendation
Consider applying the same mechanism used for requesting and applying onchain unregister routers. For example:
apply_withdraw function: ;fn apply_withdraw(ref self: ComponentState<TContractState>, signed_withdraw: SignedWithdraw, gas_price:u256, cur_gas_per_action:u32) {
//...
+let key = (signed_withdraw.withdraw.token, signed_withdraw.withdraw.maker);
-let (delay, w_req):(SlowModeDelay, Withdraw) = self.pending_reqs.read((signed_withdraw.withdraw.token, signed_withdraw.withdraw.maker));
+let (delay, w_req):(SlowModeDelay, Withdraw) = self.pending_reqs.read(key);
assert!(!self.completed_reqs.read(hash), "ALREADY_COMPLETED: withdraw (hash = {})", hash);
// @audit clear the pending_reqs
+self.pending_reqs.write(key, SlowModeDelay{block:0,ts:0});
// ...
}request_onchain_withdraw function to ensure that there is no ongoing pending request for withdrawal: ;let (pending_ts, w_prev): (SlowModeDelay, Withdraw) = self.pending_reqs.read(key);`
+assert!(pending_ts.block == 0, "ONCHAIN_WITHDRAW_ALREADY_REQUESTED: ...");Resolution
In this circumstance, the user may fix this issue by depositing funds back and fixing the pending withdrawal. As the Exchange does not charge a withdrawal fee, the User will only be losing out on gas in this scenario.
For a better user experience, the logic for apply_withdraw has been adjusted to invalidate any pending withdrawal if the user applies a withdrawal that is different from the scheduled one. This change will also apply if user wishes to invalidate their pending withdrawal.
See pull request #25 in commit: 94e206a70595e10428486449bca9b4432d9c5d16
| File | Fix commit | Type | Status |
src/WithdrawComponent.cairo | — | Low | Fixed |
The on-chain withdrawal relies on pending requests that the user needs to create before withdrawing. However, the request_onchain_withdraw function does not verify the receiver address where the tokens will be transferred to.
fn request_onchain_withdraw(ref self: ComponentState<TContractState>, withdraw: Withdraw) {
// @audit check if withdraw.receiver is not address zero. This validation is not applied in this function.
assert!(get_caller_address() == withdraw.maker, "WRONG_MAKER: withdraw maker ({}) should be equal caller ({})", withdraw.maker, get_caller_address());
assert!(withdraw.amount > 0, "WITHDRAW_CANT_BE_ZERO");
// ...
assert!(w_prev != withdraw, "ALREADY_REQUESTED: withdraw for this token already requested");
assert!(w_prev.amount == 0 || self.completed_reqs.read(w_prev.get_message_hash(w_prev.maker)), "NOT_YET_COMPLETED_PREV: previous withdraw has not been completed yet");
assert!(!self.completed_reqs.read(w_hash), "ALREADY_COMPLETED: requested withdraw has already been completed");
// ...
}When the caller invokes apply_onchain_withdraw, the function gets the pending request created for the particular token by request_onchain_withdraw.
fn apply_onchain_withdraw(ref self: ComponentState<TContractState>, token:ContractAddress, key:felt252) {
let caller = get_caller_address();
let (delay, w_req): (SlowModeDelay,Withdraw) = self.pending_reqs.read((token, caller));
// ...
self._transfer(w_req, key, w_req.amount, 0, true);
}Once the user requests an on-chain withdraw, the receiver can not be changed and the apply_onchain_withdraw function reverts since the function ERC20.transfer reverts when receiver is zero address.
fn _transfer(ref self: ComponentState<TContractState>, w_req:Withdraw, w_hash:felt252, tfer_amount:u256, gas_price:u256, direct:bool) {
// ...
erc20.transfer(w_req.receiver, tfer_amount);
// ...
}Recommendation
Validate the receiver address in request_onchain_withdraw.
Resolution
Added suggested asserts in pull request #25 in commit 94e206a70595e10428486449bca9b4432d9c5d16
| File | Fix commit | Type | Status |
src/EcosystemTradeComponent.cairo | — | Low | Fixed |
When an order is matched that uses external funds, a router must sign the order, and it should not fail during execution otherwise the router will be punished. The punishment is a percentage of the charged fee that the order would have cost to execute multiplied by two, and then split between the protocol fee recipient address and the maker order address.
fn punish_router_simple(...) {
//...
// Punishment is a percentage of the gas cost
let charged_fee = gas_fee.gas_per_action.into()
* gas_px
* router.get_punishment_factor_bips().into()
/ 10000;
if charged_fee == 0 { return; }
// Router loses 2x the charged fee
// One half goes to protocol, other half goes to maker order address
router.burn(router_addr, native_base_token, 2 * charged_fee);
balancer.mint(balancer.fee_recipient.read(), charged_fee, native_base_token);
balancer.mint(maker, charged_fee, native_base_token);
// ...
}As part of the calculation for charged_fee the gas price is multiplied by the gas per action. The gas_px argument is provided by the caller which is a trusted whitelisted invoker address, however the gas_per_action is provided from the gas_fee field from the taker order’s data. This allows a taker to arbitrarily control the punishment fee that a router would incur if execution of an order failed.
To avoid punishments, the router is expected to verify that the taker’s order is valid by simulating it’s execution. A taker can construct a custom smart wallet implementation that will return a valid signature on simulation, but fail during execution. This can be done by inspecting the get_tx_info().unbox().version field and checking for the "simulate" bit at position 128. Another approach could be to simply use a regular contract instead, where the function is_valid_signature can access state and arbitrarily return whether a signature is valid or not.
Since the punishment fee imposed on the router is split between the protocol and the maker order, an attacker can construct a maker order and a taker order that will immediately match with each other. The taker order would have a gas_fee.gas_per_action which is set to a value such that after it is multiplied with the current gas_px, adjusted by the punishment factor and multiplied by two, is equal (or very close to) the balance of the router address. When the punishment is applied, the attacker will receive half of the unclaimed fees belonging to the router since the maker order also belongs to them.
This finding relies on offchain components to behave a certain way to be feasible. The router must accept user order data rather than generating data and submitting it to the user to sign. The router also should miss validity checks on the gas steps field. Validations on the expected execution cost would need to check for profit after execution, with no upper bounds (if user offers excessive gas payment it would accept). In order to profit from this attack, an attacker must match their own taker and maker order, which may be challenging depending on factors such as spread and volatility. If the attacker’s taker order matches with another user’s maker order, they will receive the stolen funds instead.
In summary, an attacker can construct self-matching maker/taker orders and manipulate their gas_per_action field with a specific value that will result in the punishment fee being equal to a router’s unclaimed fee balance. The attacker can guarantee that punishment will occur by using a custom wallet implementation, and when the punishment is applied they will receive half of the router’s unclaimed fees.
Recommendation
Consider adjusting the punish_router_simple function to use the cur_gas_per_action argument provided by the whitelisted invoker inapply_single_taker, instead of using the untrusted gas_per_action provided by the taker order. This will prevent the punishment fee from being controlled by the taker order.
Resolution
This issue relates only to the unclaimed portion of fees the Router earns through orders routed to LayerAkira.
The likelihood of these fees getting drained is highly unlikely and would only arise in a scenario where the maker, taker and exchange all act negligently / maliciously. This is because:
The suggested asserts have also been implemented to make this scenario even more unlikely in pull request #25 commit de4853abe8e3ff9a6d75ca3b38db20af757b9f6d.
| File | Fix commit | Type | Status |
src/LayerAkira | — | Low | Fixed |
The owner calls update_fee_recipient to update the fee recipient address. The fee_recipient receives tokens from the users when they pay fees. However, the owner could set a zero address by mistake since the function does not check the new_fee_recipient value. The owner can easily fix this issue, but the protocol may lose tokens until the problem is detected.
#[external(v0)]
fn update_fee_recipient(ref self: ContractState, new_fee_recipient: ContractAddress) {
assert!(self.owner.read() == get_caller_address(), "Access denied: update_fee_recipient is only for the owner's use");
// @audit fee_recipient should always be different from zero
// since fees are transferred to this address
self.balancer_s.fee_recipient.write(new_fee_recipient);
self.emit(FeeRecipientUpdate{new_fee_recipient});
}Recommendation
Consider adding a check if new_fee_recipient is not zero address.
Resolution
We have addressed the recommendation in pull request #25 in commit 94e206a70595e10428486449bca9b4432d9c5d16
| File | Fix commit | Type | Status |
src/LayerAkira.cairo | — | Info | Fixed |
Before filling orders, generic_taker_check(...) validates if maker and taker are using the same exchange version and to update the contract’s version, only versions higher than the current one are allowed:
fn update_exchange_version(... , new_version:u16) {
// @audit Condition to enforce version incrementation
assert!(new_version > self.exchange_version.read(), "Exchange version can only increase");
// ...
}The problem is that in case of malicious or unintentional upgrade to u16 maximum value the contract won’t admit new exchange versions.
Recommendation
Add a validation in update_exchange_version to restrict the difference between the current and new version numbers.
Resolution
Addressed in pull request #25 commit f4ee3230a2c99b22398de5027bcd4adcad804fb4. The field has been removed as it no longer has any business logic behind it. The signature logic was adjusted to factor in the account contract address. This will avoid replicating fills of orders that users submit for the original exchange. Users can be assured that the orders they sign are only valid on the particular version of the exchange.
| File | Fix commit | Type | Status |
src/Order.cairo | — | Info | Mitigated |
A good-after-time (GAT) order is a trading instruction which can be combined with market orders, limit orders and other order types. A GAT order instructs to wait until a predetermined time or date has transpired before order become valid.
To create an order, market participants specify creation and duration timestamps that define the time period in which the order is considered valid and can be filled by takers. The timestamps are validated in do_maker_checks(...) and generic_taker_check(...) functions as part of the order fulfilment process. The problem is that these functions lack checks to determine if the current timestamp is greater than the created_at attribute of the order.
fn do_maker_checks(...) {
// ...
// @audit This condition just validates the end of valid time.
assert!(get_block_timestamp() < maker_order.constraints.created_at.into() + maker_order.constraints.duration_valid.into(), "Maker order expire {}", maker_order.constraints.duration_valid);
// ...
}
fn generic_taker_check(...) {
// ...
// @audit This condition just validates the end of valid time.
assert!(get_block_timestamp() < taker_order.constraints.created_at.into() + taker_order.constraints.duration_valid.into(), "Taker order expire {}", taker_order.constraints.duration_valid);
}Recommendation
Before filling the order, consider validating that the timestamp is greater or equal to the order creation timestamp.
Resolution
This issue is addressed with the Exchange’s off-chain validation logic. When orders are sent to the Exchange, orders created too early are marked as stale and therefore not processed. This check was moved off-chain so that it does not present friction when the Exchange is performing rollups.
_transfer function| File | Fix commit | Type | Status |
src/WithdrawComponent.cairo | — | Info | Fixed |
The function _transfer is called during withdrawals. This function receives the boolean parameter direct.
fn _transfer(ref self: ComponentState<TContractState>,
w_req:Withdraw,
w_hash:felt252,
tfer_amount:u256,
gas_price:u256,
direct:bool) {
// ...
}The apply_withdraw function calls _transfer, passing the value of the comparison of w_req == signed_withdraw.withdraw. As presented below, it invokes _transfer, w_req always equal to signed_withdraw.withdraw.
fn apply_withdraw(ref self: ComponentState<TContractState>, signed_withdraw: SignedWithdraw, gas_price:u256, cur_gas_per_action:u32) {
let hash = signed_withdraw.withdraw.get_message_hash(signed_withdraw.withdraw.maker);
let (delay, w_req):(SlowModeDelay, Withdraw) = self.pending_reqs.read((signed_withdraw.withdraw.token, signed_withdraw.withdraw.maker));
// ...
// @audit w_req is now equal to signed_withdraw.withdraw
let w_req = signed_withdraw.withdraw;
// ...
// @audit-info Tautology: the result of w_req == signed_withdraw.withdraw is always true
self._transfer(w_req, hash, tfer_amount, gas_price, w_req == signed_withdraw.withdraw);
}Similarly, the apply_onchain_withdraw function always passes true to _transfer.
fn apply_onchain_withdraw(ref self: ComponentState<TContractState>, token:ContractAddress, key:felt252) {
// ...
self._transfer(w_req, key, w_req.amount, 0, true);
}Recommendation
Consider removing this parameter or reevaluating the goal for the direct parameter.
Resolution
The apply_onchain_withdraw function always passes true to _transfer because this flag in the event indicates the origin of the withdrawal, whether it is generated off-chain or on-chain. Since apply_onchain_withdraw is on-chain, the flag is always set to true.
In contrast, when the exchange performs a rollup with user withdrawals, the exchange need to distinguish whether it is the finalization of an on-chain withdrawal or purely an off-chain one. This has now been addressed by performing this comparison before reassigning w_req to signed_withdraw.withdraw.
Addressed in pull request #25 in commit 94e206a70595e10428486449bca9b4432d9c5d16
_do_part_external_taker_validate function validates taker order’s nonce with itself| File | Fix commit | Type | Status |
src/EcosystemTradeComponent.cairo | — | Info | Fixed |
The function apply_single_taker invokes _do_part_external_taker_validate when the taker order defines that the source of the funds to execute the trade are not from the balance of the Exchange, i.e., it is flagged external_funds=true. As presented below, _do_part_external_taker_validate calls generic_taker_check function to validate data related to taker orders.
fn _do_part_external_taker_validate(self:@ComponentState<TContractState>,
signed_taker_order:SignedOrder, swaps:u16, version: u16, fee_recipient:ContractAddress) -> (Order,felt252,OrderTradeInfo, u256) {
// ...
// @audit the taker_order's nonce is passed instead the one in NonceComponent.get_nonce(taker_order.maker)
super::generic_taker_check(taker_order, taker_fill_info, taker_order.constraints.nonce, swaps, taker_hash, version, fee_recipient);
// ...
}The generic_taker_check function receives several information associated to the taker order, such as the taker_order and the nonce of the current order (instead get from NonceComponent.get_nonce(taker_order.maker). Then, the function checks whether the taker orders’ nonce is greater than or equal to nonce. This checking will be always true, since the nonce parameter represents the nonce assigned in the taker order.
fn generic_taker_check(taker_order:Order, taker_fill_info:OrderTradeInfo, nonce:u32, swaps:u16, taker_order_hash:felt252, version:u16, fee_recipient:ContractAddress) {
// ...
assert!(taker_order.constraints.nonce >= nonce, "OLD_TAKER_NONCE");
// ...
}This error does not trigger any vulnerability because the taker’s nonce is correctly implemented in the _prepare_router_taker function that is called later by apply_single_taker. However, _do_part_external_taker_validate may be reused somewhere in future changes and it could add issues.
Recommendation
Consider applying the following change:
-super::generic_taker_check(taker_order, taker_fill_info, taker_order.constraints.nonce, swaps, taker_hash, version, fee_recipient);
+super::generic_taker_check(taker_order, taker_fill_info, contract.get_nonce(taker_order.maker), swaps, taker_hash, version, fee_recipient);Resolution
Addressed in pull request #25 in commit de4853abe8e3ff9a6d75ca3b38db20af757b9f6d.
| File | Fix commit | Type | Status |
src/LayerAkira.cairo | — | Best Practices | Fixed |
The owner invokes update_exchange_version to update the exchange version. When the caller is not the owner, it triggers an error message of access denied to the update_exchange_invorkers function instead of update_exchange_version.
#[external(v0)]
fn update_exchange_version(ref self: ContractState, new_version:u16) {
// @audit the error message is referring to update_exchange_invokers function
assert!(self.owner.read() == get_caller_address(), "Access denied: update_exchange_invokers is only for the owner's use");
assert!(new_version > self.exchange_version.read(), "Exchange version can only increase");
self.exchange_version.write(new_version);
self.emit(VersionUpdate{new_version});
}Recommendation
Consider adapting the error message to the proper function.
Resolution
Adapted the error message to the properly function in pull request #25 in commit 94e206a70595e10428486449bca9b4432d9c5d16
bind_to_signer does not check signer address| File | Fix commit | Type | Status |
src/SignerComponent.cairo | — | Best Practices | Fixed |
The caller invokes bind_to_signer function to set a signer. The function checks if the signer is already set, updates the storage, and emits an event with the trader account and signer. However, it does not check whether signer is different from zero address.
fn bind_to_signer(ref self: ComponentState<TContractState>, signer: ContractAddress) {
let caller = get_caller_address();
// @audit check if signer is not zero address
assert!(self.trader_to_signer.read(caller) == 0.try_into().unwrap(), "ALREADY BINDED: signer = {}", self.trader_to_signer.read(caller));
self.trader_to_signer.write(caller, signer);
self.emit(NewBinding { trading_account: caller, signer: signer });
}Recommendation
Consider checking if signer is not a zero address.
Resolution
Addressed recommendation in pull request #25 in commit 94e206a70595e10428486449bca9b4432d9c5d16
self.trader_to_signer.read(caller) == 0.try_into().unwrap()| File | Fix commit | Type | Status |
src/* | — | Best Practices | Fixed |
The following is a list of functions, variables and comments that can be corrected:
EcosystemTradeComponent.cairo
can_tranfer -> can_transfer;trasfer_in -> transfer_in;trasfer_back -> transfer_back;apply_fixed_fees, MOSMATCH -> MISMATCH;Recommendation
Consider implementing the corrections mentioned above.
Resolution
Addressed in pull request #25 in commit de4853abe8e3ff9a6d75ca3b38db20af757b9f6d
| File | Fix commit | Type | Status |
src/Order.cairo | — | Best Practices | Fixed |
The function do_maker_checks applies redundant checking for full_fill_only. It asserts that the maker_order is not full_fill_only. However, when the flag post_only = true, the function applies again the same checking.
fn do_maker_checks(maker_order:Order, maker_fill_info:OrderTradeInfo, nonce:u32,fee_recipient:ContractAddress)-> (u256, u256) {
// ...
assert!(!maker_order.flags.full_fill_only, "WRONG_MAKER_FLAG: maker_order can't be full_fill_only");
assert!(get_block_timestamp() < maker_order.constraints.created_at.into() + maker_order.constraints.duration_valid.into(), "Maker order expire {}", maker_order.constraints.duration_valid);
if maker_order.flags.post_only {
// @audit Redundant checking for !maker_order.flags.full_fill_only
// at this point, maker_order.flags.full_fill_only == false (it was checked above in the function)
assert!(!maker_order.flags.best_level_only && !maker_order.flags.full_fill_only, "WRONG_MAKER_FLAGS");
}
// ...
}Recommendation
Consider removing the redundant checking.
Resolution
Addressed in pull request #25 in commit de4853abe8e3ff9a6d75ca3b38db20af757b9f6d.
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.
The documentation for LayerAkira is available on LayerAkira gitbook. It consists of sections with:
| 39Tests 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