Influence
SWAY Token

SWAY is the ERC-20 token behind the game Influence, written in Cairo. We reviewed its transfer-volume tracking, access control, L1 to L2 bridging logic and upgradeability.
report id
0258
category
Token & RWA
language
Cairo
final report
June 20, 2024
lines of code
633
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind Security for the INFLUENCETH SWAY contract. SWAY is an ERC-20 contract written in Cairo language. Apart from the standard ERC-20 operations, the contract also implements:

  • A mechanism to keep the history of the transfers during a given period of time. In the audited version, this value corresponds to 1,000,000 (one million seconds, i.e., something around 11.5 days);
  • Access Control allowing for minting and setting operational parameters;
  • Logic for bridging assets between Layers 1 and 2;
  • This version can update the contract.

The audited code comprises 648 lines of code in Cairo. The INFLUENCETH team has provided documentation explaining the audited contracts’ purpose and functionality. The audit was conducted using: (a) manual analysis of the codebase; (b) simulation of the smart contracts; and (c) evaluation of the test suite along with the creation of new test cases.

Throughout this document, we highlight five points of attention, classified as Info. Four out of these five points have been fixed by the SWAY team. The remaining issue pertains to the risk of malicious users artificially inflating the volume of transfers per period, which cannot be mitigated.

Audit assessment
Audit TypeSecurity Review
Initial ReportJun 19, 2024
Final ReportJun 20, 2024
MethodsManual Review, Automated analysis, Creation of test cases
RepositorySWAY
Commit Hashd6d5262dcf
Final Commit Hashcd9a523295
DocumentationINFLUENCETH wiki
Documentation AssessmentMedium
Test Suite AssessmentMedium
Total findings
5
Fixed
4
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low0
  • Informational5
  • Best Practices0

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/contracts/sway.cairo63312720.1%168928
Total63312720.1%168928

4

System Overview

SWAY implements an ERC-20 contract plus bridging functionalities and a mechanism to keep track of the total value transfered in periods of 1,000,000 seconds (something around 11.5 days). The interface for the ERC-20 functions are reproduced below.

fn allowance(self: @TContractState, owner: ContractAddress, spender: ContractAddress) -> u256;
fn approve(ref self: TContractState, spender: ContractAddress, amount: u256) -> bool;
fn balance_of(self: @TContractState, account: ContractAddress) -> u256;
fn balanceOf(self: @TContractState, account: ContractAddress) -> u256;
fn decimals(self: @TContractState) -> u8;
fn decrease_allowance(ref self: TContractState, spender: ContractAddress, subtracted_value: u256);
fn decreaseAllowance(ref self: TContractState, spender: ContractAddress, subtracted_value: u256);
fn increase_allowance(ref self: TContractState, spender: ContractAddress, added_value: u256);
fn increaseAllowance(ref self: TContractState, spender: ContractAddress, added_value: u256);
fn name(self: @TContractState) -> felt252;
fn symbol(self: @TContractState) -> felt252;
fn total_supply(self: @TContractState) -> u256;
fn totalSupply(self: @TContractState) -> u256;
fn transfer(ref self: TContractState, recipient: ContractAddress, amount: u256) -> bool;
fn transfer_from(ref self: TContractState, sender: ContractAddress, recipient: ContractAddress, amount: u256) -> bool;
fn transferFrom(ref self: TContractState, sender: ContractAddress, recipient: ContractAddress, amount: u256) -> bool;
fn mint(ref self: TContractState, recipient: ContractAddress, amount: u256);
}

The contract also implements special transfer functions with a confirmation scheme. The header of these functions is shown below.

fn transfer_with_confirmation(
ref self: TContractState,
recipient: ContractAddress,
amount: u128,
memo: felt252,
consumer: ContractAddress
) -> bool;

fn transfer_from_with_confirmation(
ref self: TContractState,
sender: ContractAddress,
recipient: ContractAddress,
amount: u128,
memo: felt252,
consumer: ContractAddress
) -> bool;

fn confirm_receipt(
ref self: TContractState, sender: ContractAddress, recipient: ContractAddress, amount: u128, memo: felt252
);

The contract also implements access control via the functions shown below.

fn add_grant(ref self: TContractState, account: ContractAddress, role: u64);
fn has_grant(self: @TContractState, account: ContractAddress, role: u64) -> bool;
fn revoke_grant(ref self: TContractState, account: ContractAddress, role: u64);

Finally, we have the code responsible for bridging assets between the layers.

fn get_l1_bridge(self: @TContractState) -> EthAddress;
fn get_l2_token(self: @TContractState) -> ContractAddress;
fn set_l1_bridge(ref self: TContractState, l1_bridge: EthAddress);
fn initiate_withdrawal(ref self: TContractState, l1_recipient: EthAddress, amount: u256);
fn handle_deposit(ref self: TContractState,
from_address: felt252, // L1 Bridge
to_address: ContractAddress, // L2 destination account
amount_low: felt252, amount_high: felt252 );

fn set_l1_sway_address(ref self: TContractState, l1_sway_address: EthAddress);
fn set_l1_sway_volume_address(ref self: TContractState, l1_sway_volume_address: EthAddress);

4.1 Contract Storage

The contract storage is composed of the following fields.

#[storage]
struct Storage {
_decimals: u8,
_name: felt252,
_symbol: felt252,
_total_supply: u256,
allowances: LegacyMap::<(ContractAddress, ContractAddress), u256>,
balances: LegacyMap::<ContractAddress, u256>,
confirmations: LegacyMap::<felt252, felt252>,
l1_bridge_address: EthAddress,
l1_sway_volume_address: EthAddress,
period_volumes: LegacyMap::<u64, u256>,
role_grants: LegacyMap::<(ContractAddress, u64), bool>,
}

We can notice that standard elements of an ERC-20 contract, such as _decimals, _name, _symbol, _total_supply, allowances mapping, and the balances mapping.

We also notice fields required to implement the complementary functionalities:

confirmations: LegacyMap::<felt252, felt252>,         // implements the mapping used for transfer confirmations;
l1_bridge_address: EthAddress, // stores the address of the L1 bridge;
l1_sway_address: EthAddress,
l1_sway_volume_address: EthAddress, // address of the swai contract in Layer 1;
period_volumes: LegacyMap::<u64, u256>, // stores the volume of transfers of each 1_000_000 seconds window;
role_grants: LegacyMap::<(ContractAddress, u64), bool>, // mapping for access control

4.2 Events

The contract also emits the following events.

enum Event {
Transfer: Transfer,
Approval: Approval,
DepositHandled: DepositHandled,
WithdrawInitiated: WithdrawInitiated,
ConfirmationCreated: ConfirmationCreated,
ReceiptConfirmed: ReceiptConfirmed
}

We recommend the contract to also emit events when updating the end-points of the bridge.

5

Risk Rating Methodology

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

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

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

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

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

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

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

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

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

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

6

Issues

6.1 Centralization risks

FileFix commitTypeStatus
src/contracts/sway.cairo—InfoFixed

Centralization risks in smart contracts refer to drawbacks associated with a high degree of control or influence held by a single entity or a small group of entities within the smart contract. The contract has an administrator who can execute special actions without the consent of users. For instance, the administrator can mint, upgrade the contract, change the bridge address, and add/remove new administrators.

Recommendation

We suggest updating the user-facing documentation to explain the situations when the administrator can take these special actions.

Resolution

Notes have been added to make clear that the initial admin role will be revoked after the audit is complete.

6.2 Consider emitting when updating the end-points of the bridge

FileFix commitTypeStatus
src/contracts/sway.cairo—InfoFixed

The administrator (ADMIN) can update the address of the L1 bridge. This operation is critical, and it would be advantageous for the contract to emit an event each time the bridge address is updated. The code, including audit comments, is provided below.

#[external(v0)]
fn set_l1_bridge(ref self: ContractState, l1_bridge: EthAddress) {
///////////////////////////////////
// @audit: consider emiting here
///////////////////////////////////
assert(self.role_grants.read((get_caller_address(), roles::ADMIN)), 'SWAY: must be admin');
self.l1_bridge_address.write(l1_bridge);
}

Recommendation

Consider emiting an event whenever the bridge address is updated.

Resolution

An emitted event has been added:

#[derive(Drop, starknet::Event)]
struct L1BridgeUpdated {
address: EthAddress
}

#[external(v0)]
fn set_l1_bridge(ref self: ContractState, l1_bridge: EthAddress) {
assert(self.role_grants.read((get_caller_address(), roles::ADMIN)), 'SWAY: must be admin');
self.l1_bridge_address.write(l1_bridge);
self.emit(L1BridgeUpdated { address: l1_bridge });
}

6.3 Unused storage variable l1_sway_address

FileFix commitTypeStatus
src/contracts/sway.cairo—InfoFixed

The storage variable l1_sway_address is never used.

Recommendation

Remove the unused variable.

Resolution

This variable was deprecated once the determination was made not to use a monolithic token / bridge on L1, it has been removed along with its setter.

6.4 Using zero value as memo can lead to transfers without confirmation

FileFix commitTypeStatus
src/contracts/sway.cairo—InfoFixed

The transfer_with_confirmation(...) function does not ensure that memo is non-zero. This oversight allows users to make transfers through transfer_with_confirmation(...) without effectively creating a confirmation. The function is shown below.

fn transfer_with_confirmation(
ref self: ContractState,
recipient: ContractAddress,
amount: u128,
memo: felt252,
consumer: ContractAddress
) -> bool {
let caller_address: ContractAddress = starknet::get_caller_address();

let mut to_hash: Array<felt252> = Default::default();
to_hash.append(caller_address.into());
to_hash.append(recipient.into());
to_hash.append(amount.into());
///////////////////////////////////////////////////
// @audit: missing validation for field "memo"
///////////////////////////////////////////////////
to_hash.append(memo);
to_hash.append(consumer.into());
let hashed = poseidon::poseidon_hash_span(to_hash.span());

assert(self.confirmations.read(hashed) == 0, 'SWAY: already confirmed');
self.confirmations.write(hashed, memo);
transfer(ref self, recipient, amount.into());

self.emit(ConfirmationCreated {
from: caller_address,
to: recipient,
value: amount,
memo: memo,
consumer: consumer
});

return true;
}

Recommendation

Ensure that memo is different from zero.

Resolution

We don’t think it’s a problem, as, in general, it’s in the sending account’s best interest to include the correct memo (since the receipt is confirmed by the game contract in their favor), but we agree it’s unexpected behavior. We have added an assertion that the memo is present.

6.5 Volume of transactions can be artificially inflated

FileFix commitTypeStatus
src/contracts/sway.cairo—InfoAcknowledged

Sway tracks the amount transferred in each 1-million-second period. Malicious users can transfer funds between their accounts to artificially inflate the transaction volume during a given period.

Recommendation

This cannot be prevented. Users can always create more accounts and transfer funds between them. This is intrinsic to any system that allows transfers between users.

Resolution

Unavoidable (intrinsic feature of any system that allows transfers between users)

After discussion with the team, we concluded that only a few parties (initially us, and subsequently other builders benefiting from SWAY emissions) could gain from this. Due to how emissions adjust to target the long-term moving average, our modeling showed minimal potential net gain.

7

Documentation Evaluation

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

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

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

8

Remarks & Test Suite

The SWAY has provided documentation about the protocol through in-line comments. Additionally, the SWAY team was available to address any questions or concerns from the Nethermind Security team.

The SWAY module is part of a system. The system has many test cases. In this section, we highlight the test cases related to SWAY.

8.1 Complementary Tests

We developed several test cases to validate the correct behavior of SWAY. To test the functionality of recording the volume of transfers per period, we created a mock block.timestamp variable. This allowed us to alter the current timestamp to ensure that the storage variable period_volumes is being properly populated. Below, we show the declaration of period_volumes and the new mock variable _block_timestamp.

To set and read the block.timestamp, we created the functions below. The test case below checks the infinite allowance and tries to transfer tokens between users without allowance. SWAY passes this test. The test case below checks the functionality of storing the amount transferred per period. SWAY also passes this test.

Remarks about SWAY tests

In summary, the protocol has a very complete test suite.

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.