Download audit report
This document presents the security review performed by Nethermind on the ZKX Starkway. The reviewed contracts implement the Starkway, a mechanism that facilitates the transfer of ERC20 tokens between Ethereum and Starknet while also introducing distinctive features that enhance user interaction. The Starkway allows users to seamlessly transfer any ERC20 token from Ethereum to Starknet without requiring permission. If the token is not already present on Starknet, it is automatically deployed and initialized. Furthermore, the Starkway extends its functionality by permitting the execution of arbitrary calls by transmitting messages in conjunction with the deposit to Starknet. This opens up opportunities for the integration of Starkway in sophisticated cross-chain applications.
All fixes by the ZKX team were provided in the audit-fixes branch at commit 5564a902f10056d73d074789f00f5f5f9d69cdd4 which have been reviewed by Nethermind and merged into the main development branch.
The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contract, and (d) creation of test cases.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Sep. 27, 2023 |
| Response from Client | Nov. 17, 2023 |
| Final Report | Dec. 05, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | starkway_v2 |
| Commit (Audit) | f933f5980b |
| Branch (Fix Review) | audit-fixes |
| Commit (Final) | 5564a902f1 |
| Documentation Assessment | Medium |
| Test Suite Assessment | Medium |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | L2/src/utils.cairo | 1 | 0 | 0.0% | 0 | 1 |
| 2 | L2/src/starkway.cairo | 1009 | 297 | 29.4% | 177 | 1483 |
| 3 | L2/src/datatypes.cairo | 94 | 4 | 4.3% | 15 | 113 |
| 4 | L2/src/bridge_adapters.cairo | 1 | 0 | 0.0% | 0 | 1 |
| 5 | L2/src/interfaces.cairo | 186 | 30 | 16.1% | 13 | 229 |
| 6 | L2/src/lib.cairo | 11 | 0 | 0.0% | 0 | 11 |
| 7 | L2/src/libraries.cairo | 2 | 0 | 0.0% | 0 | 2 |
| 8 | L2/src/starkway_helper.cairo | 151 | 57 | 37.7% | 39 | 247 |
| 9 | L2/src/admin_auth.cairo | 128 | 43 | 33.6% | 32 | 203 |
| 10 | L2/src/plugins.cairo | 5 | 0 | 0.0% | 1 | 6 |
| 11 | L2/src/erc20.cairo | 1 | 0 | 0.0% | 0 | 1 |
| 12 | L2/src/erc20/erc20.cairo | 222 | 20 | 9.0% | 39 | 281 |
| 13 | L2/src/utils/helpers.cairo | 69 | 15 | 21.7% | 15 | 99 |
| 14 | L2/src/bridge_adapters/starkgate_adapter.cairo | 32 | 0 | 0.0% | 4 | 36 |
| 15 | L2/src/libraries/fee_library.cairo | 100 | 12 | 12.0% | 19 | 131 |
| 16 | L2/src/libraries/reentrancy_guard.cairo | 19 | 6 | 31.6% | 4 | 29 |
| Total | 2031 | 484 | 23.8% | 358 | 2873 |
The Starkway protocol can be split into the Ethereum and Starknet layers. It enables users to transfer ERC20 tokens from Ethereum to Starknet permissionless. If the token has not been deployed on Starknet, the protocol automatically initiates the deployment and initialization of the token. Alongside the deployment of funds, Starkway also allows for transmitting arbitrary call messages to Layer 2 (L2), thereby facilitating complex cross-chain interactions. The protocol is not limited to bridging tokens back to Ethereum for native (Starkway) tokens alone, but it also extends this functionality to assets from other Starknet bridges through adapters. Below, we show the contract interaction graphs for both layers and describe each contract and its purpose.
Ethereum Starknet ZKX Contract (Single)
Deposit funds Send deposit fee ZKX Contract (Many) Deposit funds Update token settings Native Token
User with message Starkway Clear token settings Owner FeeLibrary AdminAuth (ERC20)
Withdraw funds Cancel any deposit External Contract Cancel deposit Set message fee Call Mint/burn
Withdraw funds Consume withdrawal msg Transfer Check token initialized Set fee data Approve Calc initialization fee Send deposit msg Get fee data Allowance Deposit funds Cancel deposit msg Permission checks
Call with value Deposit message Send token Deposit 3rd Party
StarkwayVault initialization Starknet Starkway Withdraw Bridge Adapter Withdraw Bridge
Starkway Main L1 entrypoint which users interact with. Allows users to deposit, send, and withdraw funds by consuming L2 messages.
StarkwayVault Holds all the bridged funds and initializes new tokens on Starknet. This is the only part of the protocol that will not be upgraded.
StarkwayHelper Provides tokens metadata for StarkwayVault.
User Any address that interacts with the protocol.
Owner Special address that sets parameters and can deposit L2 message in critical cases.
ERC20 Asset An external ERC20 asset used for round asset deposits.
Starknet The Starknet contract on Ethereum which is used to communicate with the Starknet chain.
Starkway Main L2 entrypoint which users interact with. Allows funds withdrawal with native (Starkway) tokens or other supported tokens. Sends a message to L1, which then must be consumed.
FeeLibrary Provides functionality to set and read fees.
ReentrancyGuard Provides functionality to prohibit reentrancy.
AdminAuth Manages the admins of the protocol. Two different admins must confirm each addition and removal.
Native Token (ERC20) Tokens deployed by the Starkway bridge.
Bridge Adapter Those contracts allow for communication sending non-native tokens to the specified bridge.
Third Party Bridge Receives tokens from Starkway through the adapter and bridges the assets to Ethereum.
Plugin or App Executes the message sent alongside the deposit.
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 |
StarkwayVault.sol | — | Low | Acknowledged |
The Starkway protocol allows non-privileged users to initialize a token in two ways: Through a deposit or by manually calling initToken(...).
The function initToken(...) is the most direct initialization method, where you pass an address, and an initialize message is sent to the associated Starkway L2 contract. One part of the initialization checks is to ensure that a token has not already been initialized by checking the initStatusByToken mapping; however, this does not guarantee that the Starkway L2 contract processed the initialization message.
A malicious user may call initToken(...) with a msg.value of 1 Wei, which will be too low for any sequencer to accept. The StarkwayVault contract will set the initStatusByToken value to TOKEN_IS_INITIALIZED for the given token, even though the sequencers will never process the message on Starknet. The relevant functions are shown below:
function initToken(address token) external payable {
if (initStatusByToken[token] == TOKEN_IS_INITIALIZED) {
revert StarkwayVault__TokenAlreadyInitialized();
}
(string memory name, string memory symbol, uint8 decimals) = _getMetadata(token);
/////////////////////////////////////////////////////////////////////////////////////////
// @audit-issue Attacker can pass 1 Wei msg.value and sequencer will never process on L2
// The token will be considered initialized on L1, but not on L2
// It will not be possible to re-initialize due to the init check above
/////////////////////////////////////////////////////////////////////////////////////////
_performInitialization({
token: token,
name: name,
symbol: symbol,
decimals: decimals,
initFee: msg.value
});
}This causes an inconsistency between layers, where L1 considers the token initialized, but L2 does not. As such, any deposit will succeed on L1 but revert when processed on L2. This can be done on any token that has not yet been initialized.
Once the attack is done, any further attempts to initialize the token will revert due to the already-initialized validation mentioned above, requiring the token to be manually initialized on Starkway L2 by an admin.
Recommendation
Consider adding validation in _performInitialization(...) to ensure that the initFee is greater than or equal to the storage variable initMessageFee.
Resolution
We acknowledge this issue, but there’s no simple fix to it. Starknet messaging fee can’t be calculated onchain and there’s no reasonable minimum fee value to be hardcoded in the contract to solve the issue. There’s also a admin-controlled mechanism on L2 to perform token initialization if the init message fails to be consumed on the L2 side. We are going to execute a script to initialize 100+ most widely used tokens which will prevent this problem from happening.
| File | Fix commit | Type | Status |
Starkway.sol | PR #61 PR #61 | Low | Fixed |
The function _validateTokenSettings(...) checks if provided fee segments are defined correctly. One of the responsibilities of this function is ensuring the space of all allowed deposit amounts is covered by the fee segments, which is done with the following requirement statement:
if (maxDeposit > prevToAmount && prevToAmount != 0) revert InvalidMaxDeposit();The above statement checks that the last segment is within a space of allowed deposit amounts. However, the value of maxDeposit can be set as zero, which is interpreted as an unlimited amount of deposit. This allows for avoiding the revert if maxDeposit = 0 and prevToAmount != 0 because the statement maxDeposit > prevToAmount returns false, even though the maxDeposit == 0 means unlimited deposit. Consequently, it would allow for a deposit that would not be covered by any fee segment and result in reverting in the function _resolveDepositFeeRate(...).
Recommendation
Consider ensuring that the segments cover all possible deposit amounts by taking maxDeposit = 0 into account in the function _validateTokenSettings(...).
Resolution
Addressed the issue in the commit 04d46b0. Also added a test for this case: b4856aa.
| File | Fix commit | Type | Status |
Starkway.solStarkwayVault.solstarkway.cairo | PR #66 | Low | Fixed |
The Starkway bridge allows users to deposit funds from Ethereum to Starknet and initialize a bridged token if it hasn’t been deployed yet on L2. While on Ethereum, those two actions are done in one transaction, the Starknet part of a bridge receives two messages that trigger the two methods: initialize_token(...) and deposit(...). It is crucial that the initialization is executed before the deposit. However, the order of execution of submitted messages is not ensured by the order of submission. Currently, Starknet operates on just one centralized Sequencer that executes messages by order of submission. This will most likely change since the block creation and execution process is planned to be decentralized. Then, the order of execution would not be ensured by the order of submission. If the deposit message is executed before the initialization, the funds won’t be deposited, and the user will have to cancel the message on L1 manually.
Recommendation
Consider avoiding the dependence on transaction order for cross-layer messages. One possible way to mitigate this issue is sending one message to the L2 starkway contract that would both initialize and deposit the token.
Resolution
We decided to decouple init & deposit messages. It was the most challenging issue from the design perspective. We’ve considered a solution when for a deposit of an uninitialized token init and deposit L1-to-L2 messages would be merged together and sent to Starknet as a single message. But this solution required too many design changes since it’s StarkwayVault who sends init message and is responsible for token initialization, but deposit message is sent by Starkway. In that case the only available option was appending deposit payload to init message. It didn’t seem to be a good solution: it required changes on L2 side, complicated the architecture, went against segregation of responsibilities and could introduce problems for integration of the Vault with the next versions of Starkway contract.
With that in mind, we decided to decouple init and deposit operations. It means that for a successful deposit a token must be initialized already, otherwise the deposit’s going to fail. We don’t expect this limitation to significantly affect the user experience. Firstly, a token has to be initialized only once, and secondly, we’re going to execute a script initializing 100+ most widely used tokens. This solution also required minimum changes on L1 and no changes on L2 side.
Addressed the issue in 3042d80.
| File | Fix commit | Type | Status |
fee_library.cairoStarkway.sol | PR #53 PR #61 PR #61 | Low | Fixed |
Custom fee segments are enabled on both L1 and L2 contracts. However, there are significant inconsistencies in the validation of provided fee segments, which we list below:
fee_library. The L1 contract does not check for this property;300. However, only L1 Starkway contract validates that the fee rates in segments are less or equal to MAX_FEE_RATE. L2 contracts allow higher fee rates in the segments;Additionally, L1 interprets the maximum fee range 0 as infinity, whereas L2 interprets 0 as zero.
Recommendation
Consider unifying the verification of fee setting.
Resolution
L2 inconsistency addressed in 2cfd174. We now check segment fee rate <= MAX_FEE_RATE and also treat 0 as infinity on L2. L1 inconsistency addressed in 04d46b0 and a test for it added in 69b1fb8.
| File | Fix commit | Type | Status |
Starkway.solstarkway.cairo | PR #54 | Low | Fixed |
The maximum range of withdrawal on the L2 starkway can be set as 0, which is interpreted as unlimited during the set:
fn set_withdrawal_range(
ref self: ContractState, l1_token_address: EthAddress, withdrawal_range: WithdrawalRange
) {
self._verify_caller_is_admin();
let native_token_address: ContractAddress = self
.native_token_l2_address
.read(l1_token_address);
assert(native_token_address.is_non_zero(), 'SW: Token uninitialized');
let zero: u256 = u256 { low: 0, high: 0 };
// @audit-note 0 value maximum withdrawal range is valid even if the value of the minimum range is non-zero
if (withdrawal_range.max != zero) {
assert(withdrawal_range.min < withdrawal_range.max, 'SW: Invalid min and max');
}
self.withdrawal_ranges.write(l1_token_address, withdrawal_range);
}However, when the withdrawal amount is validated, the value 0 of the maximum range is interpreted not as an infinite range but as 0:
fn _verify_withdrawal_amount(
self: @ContractState, l1_token_address: EthAddress, withdrawal_amount: u256
) {
let withdrawal_range = self.withdrawal_ranges.read(l1_token_address);
let safety_threshold = withdrawal_range.max;
// @audit-note the 0 value of maximum withdrawal is not interpreted as infinity
assert(withdrawal_amount < safety_threshold, 'SW: amount > threshold');
let min_withdrawal_amount = withdrawal_range.min;
assert(min_withdrawal_amount <= withdrawal_amount, 'SW: min_withdraw > amount');
}This creates an inconsistency in setting and validating the maximum range within the L2 starkway contract. Moreover, the validation of the maximum range on L2 is inconsistent with the validation on L1 since L1 Starkway interprets the maximum range 0 as infinity.
Recommendation
Consider unifying the interpretation of the maximum range between L1 and L2 and within starkway contract between setting and validating the maximum range.
Resolution
Addressed in b6d429c. We now interpret 0 as infinity on Starkway L2.
| File | Fix commit | Type | Status |
starkway.cairo | 0a9566f | Low | Fixed |
The function set_admin_auth_address(...) is used to change the admin_auth_address, which has full control over the L2 Starkway contract. If this address is set incorrectly, it may lead to the protocol admin features being left in an unreachable state; it will not be possible to change the address again due to the caller admin requirement, as shown below:
fn set_admin_auth_address(ref self: ContractState, admin_auth_address: ContractAddress) {
///////////////////////////////////////////////////////////////////////////////
// @audit-issue One time address change with no validations
// A set-then-claim would prevent irrersible accidental changes
///////////////////////////////////////////////////////////////////////////////
self._verify_caller_is_admin();
self.admin_auth_address.write(admin_auth_address);
}Recommendation
Consider using a "set-then-claim" approach, where a new admin address is proposed, and then they must call some function to claim ownership.
Resolution
Addressed in 0a9566f. Admin can propose a new address for admin_auth and the new address has to claim the ownership by calling a separate function.
withdraw_admin_fees method updates fee_withdrawn storage variable without checking total collected fees| File | Fix commit | Type | Status |
starkway.cairo | 0879f93 | Low | Fixed |
The function withdraw_admin_fees(...) is an admin-only function that is used to withdraw feels collected by the Starkway L2 contract. As part of the fee withdrawal logic, the amount of remaining fees available to withdraw is calculated, as shown below:
fn withdraw_admin_fees(...) {
//...
let current_total_fee_collected = self.total_fee_collected.read(l1_token_address);
let current_fee_withdrawn = self.fee_withdrawn.read(l1_token_address);
////////////////////////////////////////////////////////////////////////////////////////////////
// @audit-issue `current_fee_withdrawn` can be greater than collected amount if direct transfer
////////////////////////////////////////////////////////////////////////////////////////////////
let net_fee_remaining = current_total_fee_collected - current_fee_withdrawn;
//...
}It is possible for a user to manually send tokens to the contract outside of deposit logic, which will mean that while the tokens belong to the Starkway L2 contract, no fee storage data is updated. If an admin withdrew their available fees plus the directly transferred tokens, the current_fee_withdrawn will be greater than the current_total_fee_collected, since the extra direct transfer is withdrawn but was never considered to be fees that were collected.
In this situation, for following withdrawals the admin must wait until current_total_fee_collected has accumulated enough to be greater than current_fee_withdrawn.
It should be noted that this issue is known since a commend related to this behavior exists, but the logic to address the issue has been commented:
// Below case would be triggered, if transfer of tokens happen from outside
// (which is not through deposit). Below condition prevents admin from withdrawing those tokens.
// Commenting the condition for withdrawal to happen
// assert(withdrawal_amount <= net_fee_remaining, 'SW:Amount exceeds fee remaining');Recommendation
Consider checking fee_withdrawn is less than total_fee_collected before updating storage.
Resolution
Addressed in 0879f93. The admin can withdraw any amount of fees (and extra tokens) if it has the relevant token balance irrespective of amount of fees collected. However, as pointed out in the issue, we now update fee_withdrawn after ensuring it cannot be greater than total_fee_collected. This ensures that fee_withdrawn is always <= total_fee_collected.
allConnectedTargets is never written to| File | Fix commit | Type | Status |
MultiConnectable.sol | PR #60 PR #60 | Low | Fixed |
The abstract contract MultiConnectable defines an array allConnectedTargets which should store an array of connected Starkway contracts. It is used by two functions:
getAllConnections(...): Lists all targets that have ever connected, including currently disconnected targets;_disconnect(...): Disconnects a currently connected target, ensuring at least one connected version remains;However the array allConnectedTargets is never written to, and will always remain empty. For the function getAllConnections(...) this will cause an empty array to be returned on every call, as shown below:
function getAllConnections() external view returns (ConnectionInfo[] memory) {
uint256 length = allConnectedTargets.length;
ConnectionInfo[] memory result = new ConnectionInfo[](length);
/////////////////////////////////////////////////////////////////
// @audit-issue Length will always be zero, result will be empty
/////////////////////////////////////////////////////////////////
for (uint i; i < length;) {
address target = allConnectedTargets[i];
uint256 status = statusByTarget[target];
uint256 statusDate = statusDateByTarget[target];
result[i] = ConnectionInfo({
target: target,
status: status,
statusDate: statusDate
});
unchecked { ++i; }
}
return result;
}For the function _disconnect(...), the for loop will never execute since the length of the array is zero. If the loop does not run then activeConnectionsCount will not increment, causing the active connection check to fail. A snippet from this function is shown below:
function _disconnect(address target) internal {
_checkConnectionStatus(target, STATUS_CONNECTED);
uint256 totalConnectionsCount = allConnectedTargets.length;
uint256 activeConnectionsCount;
for (uint256 i; i < totalConnectionsCount;) {
address targetAtIndex = allConnectedTargets[i];
uint256 status = statusByTarget[targetAtIndex];
if (status == STATUS_CONNECTED) {
unchecked { ++activeConnectionsCount; }
}
unchecked { ++i; }
}
////////////////////////////////////////////////////////////////////////
// @audit-issue For loop will never execute, so this will always revert
////////////////////////////////////////////////////////////////////////
if (activeConnectionsCount < 2) {
revert MultiConnectable__MustRemainConnectedVersion();
}
...
}Recommendation
The storage array allConnectedTargets should be written to when a new target is connected.
Resolution
It could become a nasty issue and could be discovered too late: when connecting a new version of Starkway of disconnecting the old one. Good catch. The issue is addressed in 6cb6571 and extensive tests covering connection-disconnection process are added in 2f57d06.
withdrawal_range cannot be bridged back to Ethereum by default| File | Fix commit | Type | Status |
starkway.cairo | e4f23a7 | Low | Fixed |
When withdrawing tokens from Starknet to Ethereum, the internal function _verify_withdrawal_amount(...) is called to ensure that the withdrawal amount is within the specified min and max range. When the max range for a given token is unset (zero), no u256 value will satisfy the safety threshold assert statement, causing every withdrawal attempt from Starknet to Ethereum to fail. The relevant code is shown below:
fn _verify_withdrawal_amount(
self: @ContractState, l1_token_address: EthAddress, withdrawal_amount: u256
) {
let withdrawal_range = self.withdrawal_ranges.read(l1_token_address);
let safety_threshold = withdrawal_range.max;
//////////////////////////////////////////////////////////////////////////////////
// @audit-issue When the withdrawal range is not set, the max is zero
// When max threshold is zero, no u256 value will satisfy the assert
//////////////////////////////////////////////////////////////////////////////////
assert(withdrawal_amount < safety_threshold, 'SW: amount > threshold');
let min_withdrawal_amount = withdrawal_range.min;
assert(min_withdrawal_amount <= withdrawal_amount, 'SW: min_withdraw > amount');
}This effectively creates a permissioned withdrawal system, where the L2 Starkway admins have to manually specify a non-zero withdrawal range to allow funds to be bridged back to L1.
Recommendation
Consider changing the _verify_withdrawal_amount(...) function to behave similarly to the Ethereum contracts, where the zero value is treated as a no-limit withdrawal. If this permissioned behavior is intended, consider creating separate, specific logic related to locking and unlocking token withdrawals rather than integrating this logic into withdrawal ranges.
Resolution
Addressed in commit e4f23a7. We now treat 0 for withdrawal_range.max as infinity. Hence, if withdrawal range has not been set, it will not stop withdrawal of any token. We also implement a permissioned withdrawal system based on the L2 token address (which is enabled by default for all tokens). For withdraw function, the L2 token should have withdrawal allowed. For withdraw_multi function all the tokens being withdrawn should have withdrawal allowed. Apart from this, can_withdraw_multi also checks that all tokens that a user wants to withdraw have withdrawal enabled. The prepare_withdrawal_lists function now considers only those tokens which have withdrawal enabled. The init_token and whitelist_token functions allow withdrawal for any token being initialized or whitelisted.
| File | Fix commit | Type | Status |
admin_auth.cairo | b2fbdd4 | Info | Fixed |
The function _update_admin_mapping(...) adds or removes an admin from a admin_lookup(...) mapping. The process requires two distinct admins, other than the managed address, to submit an action of removal or adding an address. However, the admin currently can initiate removal action of its own address, since there is no check if the caller is not the same address as the managed address.
Recommendation
Consider checking if the caller is not providing its own address when managing admin access.
Resolution
Addressed in b2fbdd4.
withdraw_multi(...)| File | Fix commit | Type | Status |
starkway.cairo | bee0be9 | Info | Fixed |
The multi-withdrawal allows for withdrawing through Starkway bridge different L2 tokens that point to the same L1 token. The function withdraw_multi(...) sums the amounts of provided tokens. If a token (native or non-native) with enough liquidity is found, it is used to bridge funds to L1. However, the withdraw_multi(...) function does not consider the decimals during the calculation of all used L2 tokens. We present the abovementioned code below:
fn _calculate_withdrawal_amount(
self: @ContractState,
transfer_list: @Array<TokenAmount>,
l1_token_address: EthAddress,
native_l2_address: ContractAddress,
) -> u256 {
let transfer_list_len = transfer_list.len();
let mut index = 0_u32;
let mut amount = u256 { low: 0, high: 0 };
loop {
if (index == transfer_list_len) {
break ();
}
if (*transfer_list.at(index).l2_address != native_l2_address) {
let token_details: L2TokenDetails = self
.whitelisted_token_details
.read(*transfer_list.at(index).l2_address);
// check that all tokens passed for withdrawal represent same l1_token_address
assert(token_details.l1_address == l1_token_address, 'SW: L1 address Mismatch');
}
assert(
*transfer_list.at(index).l1_address == l1_token_address,
'SW: Incompatible L1 addr'
);
// @audit-note amount is added without taking decimals into account
amount += *transfer_list.at(index).amount;
index += 1;
};
amount
}Consequently, with inconsistent decimals, the user or bridge may lose funds due to incorrect calculation.
Recommendation
Consider verifying that all the tokens have the same number of decimals. Alternatively, calculate the token amount in _calculate_withdrawal_amount(...) using the token’s decimals. While this scenario is rather unlikely, we strongly recommend verifying instead of trusting in third-party correctness.
Resolution
Addressed in bee0be9. Also fixes “Inconsistent zero-amount checks between L2 deposit functions”.
felt| File | Fix commit | Type | Status |
Starkway.sol | PR #59 PR #59 | Info | Fixed |
When using the function depositFundsWithMessage(...), the caller can specify a particular Starknet contract address that will receive a call with the data from the argument messagePayload. However, the contents of the messagePayload are not validated to be within the range of a felt type and may lead to messages not being consumed. A snippet from the payload builder function is shown below:
function _buildDepositWithMessagePayload(...) private pure returns (uint256[] memory) {
uint256 msgLength = messagePayload.length;
uint256[] memory payload = new uint[](9 + msgLength);
(uint256 depositLow, uint256 depositHigh) = FeltUtils.splitIntoLowHigh(deposit);
(uint256 feeLow, uint256 feeHigh) = FeltUtils.splitIntoLowHigh(depositFee);
payload[0] = uint256(uint160(token));
payload[1] = uint256(uint160(senderAddressL1));
payload[2] = recipientAddressL2;
payload[3] = depositLow;
payload[4] = depositHigh;
payload[5] = feeLow;
payload[6] = feeHigh;
// Append message
payload[7] = messageRecipientL2;
payload[8] = msgLength;
for (uint256 i; i < msgLength; ) {
///////////////////////////////////////////////////////////////////////////
// @audit-issue Each entry in the message payload should fit within a felt
///////////////////////////////////////////////////////////////////////////
payload[9 + i] = messagePayload[i];
unchecked { ++i; }
}
return payload;
}Recommendation
Consider validating the message payload in _buildDepositWithMessagePayload(...).
Resolution
The issue was addressed in 956a187. Tests for the issue were added in 90119fb.
| File | Fix commit | Type | Status |
erc20.cairo | a38d39f | Info | Fixed |
The ERC20 implementation used by Starkway native tokens has function names with snake-case, following the convention of Rust and Rust-like languages. However, most of the ERC20 tokens existing in the Starknet ecosystem still use camel-case naming. The Starkway L2 contract implementation assumes that all token functions will be in snake-case, meaning that calls to any non-native token with a camel-case name will revert.
Recommendation
Consider developing a new ERC20 implementation that supports both camel-case and snake-case methods to provide better interoperability.
Resolution
Addressed in a38d39f - we have added support for camelCase functions in the native ERC20 contract and included a field for camelCase (is_erc20_camel_case) in the L2TokenDetails struct. Interaction is done through camel case functions for non-native tokens which have this field set to true.
| File | Fix commit | Type | Status |
Starkway.cairo | 2f137ba | Info | Fixed |
The function _init_token(...) emits an event with the name "INITIALISE", where every other reference to a token being initialized using the spelling "INITIALIZE" (functions, comments, revert messages). The event name and emission are shown below:
let mut keys = ArrayTrait::new();
keys.append(l1_token_address.into());
keys.append(token_details.name);
keys.append('INITIALISE');
let mut data = ArrayTrait::new();
data.append(contract_address.into());
emit_event_syscall(keys.span(), data.span());Recommendation
Consider ensuring consistency between all contracts by changing "INITIALISE" to "INITIALIZE".
Resolution
Addressed in 2f137ba.
| File | Fix commit | Type | Status |
starkway.cairo | bee0be9 | Info | Fixed |
The starkway L2 contract features two deposit functions: deposit and depositWithMessage. These functions have inconsistent input validation, where depositWithMessage(...) ensures that the deposit amount cannot be zero, while deposit(...) does not.
Recommendation
Consider adding a zero amount validation to the deposit(...) function to improve consistency between both deposit methods.
Resolution
Addressed in bee0be9. Also fixes “Decimals are not considered during in withdraw_multi”.
FeltUtils declares duplicate constant| File | Fix commit | Type | Status |
FeltUtils.sol | PR #58 | Info | Fixed |
The library FeltUtils defined a constant LOW_BITS_MASK, which is used to help split a uint256 value into the high and low bits to assist with Starknet messaging. This constant is already defined in Constants.sol and can be imported, rather than defined again.
Recommendation
Consider removing the unnecessary LOW_BITS_MASK declaration in FeltUtils and instead import the value from
Constants.sol
Resolution
Removed the unnecessary constant in 580a57e.
admin_auth constructor allows same address for both admins| File | Fix commit | Type | Status |
admin_auth.cairo | 4a4dcfc | Info | Fixed |
When deploying the admin_auth contract, the caller must specify two addresses which will have admin privileges. The constructor does not ensure that these addresses are not the same. If the same address is passed for both arguments, it will not be possible to make any further changes to admin privileges using add_admin(...) or remove_admin(...) since another admin with a different address is required. The constructor is shown below:
#[constructor]
fn constructor(... , admin_1: ContractAddress, admin_2: ContractAddress) {
/////////////////////////////////////////////////////////////////////
// @audit-issue Can have the same address for `admin_1` and `admin_2`
/////////////////////////////////////////////////////////////////////
self.admin_lookup.write(admin_1, true);
self.admin_lookup.write(admin_2, true);
self.min_num_admins.write(2_u8);
self.current_total_admins.write(2_u8);
self.emit(Event::AdminAdded(AdminAdded { address: admin_1 }));
self.emit(Event::AdminAdded(AdminAdded { address: admin_2 }));
}Recommendation
Consider adding a check to the constructor of admin_auth to ensure that the two admin addresses are not the same.
Resolution
Addressed through 4a4dcfc. We now check that admin addresses are not zero and not the same.
| File | Fix commit | Type | Status |
admin_auth.cairoStarkway.sol | ec481f7 | Info | Fixed |
The L1 Starkway contract inherits OpenZeppelin’s Ownable contract, which allows for managing owner addresses with a one-step change mechanism. On the other side, the L2 part of the protocol utilizes admin_auth, which allows for much more secure admin management - addition or removal of admin must be done by two separate currently registered admins. This mechanism is much more secure and narrows the possibility of mistakenly changing the owner to an incorrect address or malicious action by a single admin caused by, e.g., losing a private key.
Recommendation
Consider increasing the security of the L1 owner mechanism that would not rely on a single and directly transferred owner. Increased security may be achieved by using Ownable2Step that allows two-step owner changing, or use AccessControl which can be modified by to be similar to current L2 admin management mechanism.
Resolution
Both Starkway and Starkway now inherit from Ownable2Step. Ownable2Step is available only in the latest major version of OZ contracts and requires updating the versions of Solidity and dependent packages. Hence we decided to import the necessary OZ contracts directly in our project. The changes can be found in ec481f7.
| File | Fix commit | Type | Status |
helpers/TokenUtils.sol | 5930422PR #57 PR #57 | Info | Fixed |
The transfers of funds should not happen to the zero address unless the funds are meant to be burned, which is usually done with an explicit burn function. The L1 Starkway protocol protocol checks for the 0 address for ETH transfers in the function transferFundsTo(...). However, this check is not applied for ERC20 token transfers, as presented below:
function transferFundsTo(address token, address to, uint256 amount) internal {
if (token == ETH_ADDRESS) {
// @audit-note zero address check only made for the ETH transfers
require(to != address(0));
(bool isSuccess,) = to.call{value: amount}("");
if (!isSuccess) {
revert TokenUtils__EthTransferFailed({
to: to,
value: amount
});
}
} else {
// @audit-note no check for zero address for ERC20 tokens
IERC20(token).safeTransfer(to, amount);
}
}Moreover, the zero address checks are not done on the L2 starkway contract during the funds’ withdrawal. Lack of this check may result in sending a message to L1 Starkway contract with the 0 address.
Recommendation
Consider checking if the recipient is not the 0 address consistently on both L1 and L2 contracts and for all tokens, including ERC20.
Resolution
A proposed check was added on the L2 side in 5930422. On the L1 side the issue was addressed in 421d82b and the related tests were added in 6220b53.
| File | Fix commit | Type | Status |
datatypes.cairo | 682ede0 | Best Practices | Fixed |
The custom types in datatypes derive both Drop and Destruct traits. Those traits are equivalent, with two differences: Drop can’t be derived by types with dictionaries, and is no-op meaning it does not generate CASM. Therefore the types in datatypes do not need to derive both the Destruct and Drop traits.
Recommendation
Consider deriving the correct traits for the custom types.
Resolution
Addressed in 682ede0.
| File | Fix commit | Type | Status |
datatypes.cairo | d71ca28 | Best Practices | Fixed |
The implementations TokenAmountPartialOrd and a TokenAmountPartialEq are using different syntax:
// TokenAmountPartialOrd
#[inline_always]
// TokenAmountPartialEq
#[inline(always)]Recommendation
Unify the syntax to match one Cairo version across the contracts.
Resolution
Addressed in d71ca28.
| File | Fix commit | Type | Status |
Starkway.cairo | 7db387e | Best Practices | Fixed |
Registering the bridge through the register_bridge_adapter(...) method checks that the bridge registered before with the same ID. It makes it impossible to change the address in the future. However, bridge adapters that don’t fit the current interface can be added through this method.
Recommendation
Consider checking that the contract address is a valid bridge adapter.
Resolution
Addressed in 7db387e.
everConnectedAsStarknet| File | Fix commit | Type | Status |
PairedToL2.sol | PR #63 | Best Practices | Fixed |
Storage mapping named everConnectedAsStarknet is unnecessary. It is just written once in the following lines:
function _setStarknetAddressTo(address newAddress) internal {
// ...
everConnectedAsStarknet[newAddress] = true;
// ...
}But never read from somewhere else. Also, it is an internal variable that any external view calls can’t reach this mapping.
Recommendation
Consider removing this variable and remove assigning at _setStarknetAddressTo(...) method.
Resolution
The unused storage variable was removed in bc635b4.
| File | Fix commit | Type | Status |
fee_library.cairo | 98515e3 | Best Practices | Fixed |
On FeeLibrary, default_fee_rate stored in u256 which stores into 2 slots of felt252. However, the value can be settled only in set_default_fee_rate(...), and there is a check for the new value that can not be higher than 300.
#[storage]
struct Storage {
default_fee_rate: u256, // @audit-issue: Unnecessary store of u256. Value can fit in one slot.
// ...
}
fn set_default_fee_rate(ref self: ContractState, default_fee_rate: u256) {
// @audit-issue: default_fee_rate can fit in one felt252 slot. It's better to store it in one slot.
let MAX_FEE_RATE = u256 { low: 300, high: 0 };
assert(default_fee_rate <= MAX_FEE_RATE, 'Default_fee_rate > MAX_FEE_RATE');
self.default_fee_rate.write(default_fee_rate);
}Recommendation
Consider using unsigned integer types that fit into one felt slot.
Resolution
Addressed in 98515e3. u16 data type now used instead of u256 data type.
BoundedInt to represent unsigned integer max values| File | Fix commit | Type | Status |
erc20.cairo | d050717 | Best Practices | Fixed |
The function _spend_allowance(...) will only reduce a spenders allowance if they do not already have an unlimited allowance for a given owner address. This unlimited allowance is determined by generating a bitmask representing the maximum possible value for a u128 type and comparing against both the high and low components of the u256 type, as shown below:
let ONES_MASK = 0xffffffffffffffffffffffffffffffff_u128;
let is_unlimited_allowance = ((current_allowance.low == ONES_MASK)
& (current_allowance.high == ONES_MASK));Recommendation
The function BoundedInt::max() from the Cairo core library can be used instead, as shown below:
let is_unlimited_allowance = current_allowance == integer:BoundedInt::max();Resolution
Addressed in d050717.
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 of the ZKX Starkway is provided in extensive inline comments over the code.
| 160Tests 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