Briq
NFT Sets

Briq lets users build NFTs out of individual ERC-1155 "briqs" that combine into ERC-721 sets. We reviewed the Cairo contracts behind minting, combining and transferring briqs and sets.
report id
0053
category
Token & RWA
language
Cairo
final report
June 7, 2022
lines of code
0
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the Briq Protocol project written in the Cairo Language. The project is composed of 32 contracts (note that not all of these are in-scope for this audit). The Briq Protocol is based on the ERC-1155 standard with the ability to combine these tokens together into "sets" which are based on the ERC-721 standard. Most of the interactions with the protocol occur using materials (sometimes combined with unique ids), instead of typical token id’s.

During the initial audit, we concluded that the project can benefit from better technical documentation detailing a) use cases, b) functional requirements, c) non-functional requirements, d) diagrams showing how interactions take place, and e) a more extensive test suite. The audit was carried out using manual inspection of the code base and the generation of test cases. Most of the reported issues are related to missing validations, overflow risks, and non-defensive code. The initial audit reports 33 findings.

During the re-audit phase, the client has fixed 20 issues, acknowledged 6 issues, and not fixed 7 issues. The clarification for not fixing these issues is presented along this report. Some of these issues require more time to seek a better solution, while others are planned to be fixed during a final code cleanup.

Audit assessment
Audit TypeSecurity Review
Initial ReportMay 27, 2022
Response from ClientJun 3, 2022
Final ReportJun 7, 2022
MethodsManual Review, Creation of Test Cases
Repositoryhttps://github.com/briqNFT/briq-protocol
Commit Hash (Initial Audit)fa896be142
Commit Hash (Final Audit)5368018c94
Documentationhttps://github.com/briqNFT/briq-protocol/tree/next/docs/briq
Cairo Files Reviewed (Initial Review)
Total findings
33
Fixed
20
Acknowledged
6
Mitigated
0
Unresolved
7

Findings by severity

  • Critical0
  • High10
  • Medium0
  • Low7
  • Informational16
  • Best Practices0

2

Audited Files

Cairo Files Reviewed (Initial Review)

File
contracts/briq_erc1155_like/*
contracts/library_erc721/*
contracts/set_erc721/*
contracts/upgrades/*
contracts/utilities/*
contracts/briq_impl.cairo
contracts/set_impl.cairo
contracts/types.cairo

3

Summary of Issues

#FindingSeverityUpdate
1.1Failing asserts without with_attrInfoUnresolved
1.2Incorrect contract filenameInfoFixed
1.3Privileged address can transfer on behalf of all usersInfoAcknowledged
2.1Missing events emission in balance_enumerability.cairoLowAcknowledged
2.2Unclear use case in ownerOf_(...)InfoFixed
3.1A non-fungible Briq token with token_id zero can be mintedHighFixed
3.2Potential balance reduction and/or overflow when minting fungible Briq tokensHighFixed
3.3Missing events emission in minting.cairoLowAcknowledged
3.4The privileged contract _mint_contract can be set to address(0x0)InfoAcknowledged
4.1Potential overflows in mutateFT_(...)HighFixed
4.2Fungible Briq tokens can be mutated to have a material of zeroHighFixed
4.3Non-fungible Briq tokens can be mutated to have a token_id of zeroHighFixed
4.4No balance check on converting Briq tokens from fungible to non-fungibleHighFixed
4.5Missing input validation in convertOneToNFT_(...)HighFixed
4.6New uid can be same as existing uid when mutating non-fungible Briq tokensInfoFixed
4.7Unused imports in convert_mutate.cairoInfoUnresolved
4.8Missing event emission in mutateFT_(...)InfoAcknowledged
5.1Missing input validation in transferOneNFT_(...)HighFixed
5.2Missing events emission in transferability.cairoLowAcknowledged
5.3Missing input validation in setSetAddress_(...)LowUnresolved
5.4Missing overflow checks in transferFT_(...)InfoFixed
5.5Briq token transfers can have the same sender and receiverInfoFixed
5.6Unused imports in transferability.cairoInfoUnresolved
6.1Missing input validation in transferFrom_(...)HighFixed
6.2Incorrect namespace titleInfoFixed
7.1Functions with view visibility making changes to stateInfoFixed
8.1Unused implicit argumentsInfoUnresolved
9.1No event emitted and missing input validation in proxy.constructor(...)InfoFixed
10.1No event emitted when updating RootAdminLowFixed
11.1Functions missing events emission in approvals.cairoLowUnresolved
12.1Not checking for overflow in _transfer(...)HighFixed
13.1Test function implemented inside core contractLowUnresolved
13.2Not using boolean type of value fixed to 0 or 1InfoFixed

4

System Overview

No system overview is included in this report.

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 General findings

6.1.1 Failing asserts without with_attr

FileFix commitTypeStatus
contracts/*—InfoUnresolved

Failing asserts should use with_attr to have an error message on failure to make end users understand what may be happening when transactions fail.

Recommendation

Use with_attr to add error messages to asserts that can be expected to fail during normal use of the protocol.

Resolution

Aware, intend to fix some incrementally.

6.1.2 Incorrect contract filename

The name of the file UInt256_felt_conv.cairo is incorrect, it should be named Uint256_felt_conv.cairo. This filename issue causes the test tests/set_impl_test.py to fail.

Recommendation

Rename the file UInt256_felt_conv.cairo to Uint256_felt_conv.cairo.

Resolution

Mac Os is case insensitive which is why I missed this.

6.1.3 Privileged address can transfer on behalf of all users

FileFix commitTypeStatus
contracts/briq_erc1155_like/transferability.cairo—InfoAcknowledged

The privileged address _set_backend_address is able to control all funds on behalf of any user. Although the current protocol design relies on this feature, there are no safety features in place in the event that _set_backend_address is set to an incorrect or malicious address, which can lead to asset losses.

Recommendation

Clearly state in the user facing documentation the privileges, roles, and functions that can be performed by each entity of the application. In the interest of both the users and protocol owners it is recommended to have safety features in place to prevent an incorrect or dangerous address from being set.

Resolution

Documentation will need to be updated. Not sure on possible mitigation.

6.2 contracts/briq_erc1155_like/balance_enumerability.cairo

6.2.1 Missing events emission in balance_enumerability.cairo

FileFix commitTypeStatus
contracts/briq_erc1155_like/balance_enumerability.cairo—LowAcknowledged

The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions not emitting events is presented below.

func _setTokenByOwner(...)
func _unsetTokenByOwner(...)
func _setMaterialByOwner(...)
func _maybeUnsetMaterialByOwner(...)

Recommendation

Emit events for post-deployment monitoring.

Resolution

Likely a WONTFIX for now - these can be reconstructed from other events, such as Transfer.

6.2.2 Unclear use case in ownerOf_(...)

The function balance_enumerability.ownerOf_(...) has the following inline comment.

# OZ: don't fail on res == 0, since 0 is impossible.

It is unclear why res==0 is impossible. Since this is a view function, it can be called by anyone with any input parameter passed as token_id, including non-existent tokens. The code is reproduced below.

@view
func ownerOf_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (token_id: felt) -> (owner: felt):
let (res) = _owner.read(token_id)
# OZ : don't fail on res == 0, since 0 is impossible.
return (res)
end

Recommendation

Please, clarify this use case and explain why res cannot be zero.

Resolution

This is an unclear comment. My note means that unlike the OZ / ERC1155 standard, I don’t assert 0, I just return 0. Value ’0’ is impossible for a briq token to legitimately take, and I don’t care to assert 0. Changed the comment.

6.3 contracts/briq_erc1155_like/minting.cairo

6.3.1 A non-fungible Briq token with token_id zero can be minted

FileFix commitTypeStatus
contracts/briq_erc1155_like/minting.cairo7ebfab2HighFixed

The function mintOneNFT_(...) does not have input validation to ensure that material is within the valid range of 1 to 2ˆ64 - 1. The token_id to be minted is calculated with the formula token_id = id * 2**64 + material which means that it is possible to set material and uid to values that satisfy material == (uid * 2**64) * -1 which will result in a token_id of zero, as shown in the code below:

@external
func minting.mintOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdminAndMintContract()
assert_not_zero(owner)
assert_not_zero(material)
assert_not_zero(uid)
assert_lt_felt(uid, 2**188)
# Update total supply.
let (res) = _total_supply.read(material)
_total_supply.write(material, res + 1)
# NFT conversion
let briq_token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = 0
_owner.write(briq_token_id, owner)
_setMaterialByOwner(owner, material, 0)
_setTokenByOwner(owner, material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, 0, owner, briq_token_id, 1)
return ()
end

The following test(s) can be added to tests/briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_mint_token_id_zero(briq_contract):
# The specific values that `material` and `uid` must be to create a token id of zero
maliciousMaterial = -abs(2**64)
maliciousUid = 1
maliciousTokenId = maliciousUid * 2**64 + maliciousMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=OTHER_ADDRESS, material=maliciousMaterial, uid=maliciousUid))
# Get the owner of token id `0`
zeroTokenOwner = (await briq_contract.ownerOf(0).call()).result.owner
# Assert that the owner of the zero token is now assigned to an address
assert zeroTokenOwner == OTHER_ADDRESS

It is only possible to create one of these tokens as any future mints check the owner of the "zerotoken" which will return a non-zero value. This "zerotoken" cannot be transferred or enumerated in balances as logic for checking balances relies on the token_id of zero to end recursion. However it permanently affects the user’s _materials_by_owner data as the material associated with the "zerotoken" cannot be removed.

Recommendation

The function must validate that material in within the range of 1 to 2ˆ64 - 1. Check for overflows on briq_token_id.

Resolution

Fixed in MintOneNFT_. A similar problem existed in MintFT_ that led to a weird state. Both fixed.

6.3.2 Potential balance reduction and/or overflow when minting fungible Briq tokens

FileFix commitTypeStatus
contracts/briq_erc1155_like/minting.cairo757870aHighFixed

The function mintFT_(...) does not check for overflows on the variable balance before writing to storage. Depending on the existing balance of owner different behavior will be observed. It is possible to use mintFT(...) to reduce a users balance and it is also possible to overflow a users balance to wrap around from zero to the Starknet P prime value. The code is reproduced below:

@external
func minting.mintFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, qty: felt):
_onlyAdminAndMintContract()
assert_not_zero(owner)
assert_not_zero(material)
assert_not_zero(qty)
# Update total supply.
let (res) = _total_supply.read(material)
_total_supply.write(material, res + qty)
# FT conversion
let briq_token_id = material
let (balance) = _balance.read(owner, briq_token_id)
_balance.write(owner, briq_token_id, balance + qty)
_setMaterialByOwner(owner, material, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, 0, owner, briq_token_id, qty)
return ()
end

The following test(s) can be added to tests/briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_mint_fungible_overflow_reduce_balance(briq_contract):
# Mint 100 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=100))
# Record the balance before
balanceBefore = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Mint -10 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=-10))
# Record the balance after
balanceAfter = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Calling mint with an extremely large value causes an overflow which reduces the balance
assert balanceAfter < balanceBefore
@pytest.mark.asyncio
async def test_mint_fungible_overflow_from_empty_balance(briq_contract):
# Mint -10 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=-10))
# Record the balance
balance = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Balance is extremely large
# The value of balance will specifically be the `P` prime value of Starknet minus 10
assert balance > 1000000000000000000000000000000000000000000000000000000000000

Recommendation

Assert that the argument qty in the function mintFT_(...) is a positive number.

Resolution

The balance reduction issue is fixed. A similar issue existed for total supply for both FT and NFT, and has been fixed. The problem of minting negative numbers is left in but explicited, since this is just an interface issue (equivalent to minting a huge amount of FT).

6.3.3 Missing events emission in minting.cairo

FileFix commitTypeStatus
contracts/briq_erc1155_like/minting.cairo—LowAcknowledged

The contract does not emit events for important state transitions. Events are important for post-deployment monitoring. A list of functions with missing events is presented below:

func setMintContract_(...)
func mintFT_(...)
func mintOneNFT_(...)

Recommendation

Emit events for these functions.

Resolution

SetMintContract should, the rest is reconstructed from Transfer().

6.3.4 The privileged contract _mint_contract can be set to address(0x0)

FileFix commitTypeStatus
contracts/briq_erc1155_like/minting.cairo—InfoAcknowledged

The function setMintContract_(...) allows _mint_contract to be set to address(0x0). The code is reproduced below:

@external
func minting.setMintContract_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (address: felt):
_onlyAdmin()
_mint_contract.write(address)
return ()
end

Recommendation

If this is intended functionality designed to disable minting from the _mint_contract address, it is recommended to create a separate function specifically for halting minting from _mint_contract. Otherwise, it is recommended to check that the argument address is not address(0x0).

Resolution

The contract will be removed in the genesis sale, so the code will be removed. As things stand, it is indeed just disabled and just looks odd.

6.4 contracts/briq_erc1155_like/convert_mutate.cairo

6.4.1 Potential overflows in mutateFT_(...)

In the function mutateFT_(...) the storage variables _balance and _total_supply are written without any checks to ensure that no overflows can occur. The function is reproduced below:

@external
@external
func mutateFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, qty: felt):
_onlyAdmin()
assert_not_zero(qty * (source_material - target_material))
let (balance) = _balance.read(owner, source_material)
assert_le_felt(qty, balance)
_balance.write(owner, source_material, balance - qty)
let (balance) = _balance.read(owner, target_material)
_balance.write(owner, target_material, balance + qty)
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - qty)
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + qty)
_setMaterialByOwner(owner, target_material, 0)
_maybeUnsetMaterialByOwner(owner, source_material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, source_material, qty)
TransferSingle.emit(__addr, 0, owner, target_material, qty)
return ()
end

Recommendation

Check for overflows before writing to storage. In case of overflow, revert.

6.4.2 Fungible Briq tokens can be mutated to have a material of zero

The function mutateFT_(...) does not assert that the argument target_material is not zero and allows for fungible Briq tokens to be mutated to have a material of zero. The function is reproduced below:

@external
func mutateFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, qty: felt):
_onlyAdmin()
assert_not_zero(qty * (source_material - target_material))
let (balance) = _balance.read(owner, source_material)
assert_le_felt(qty, balance)
_balance.write(owner, source_material, balance - qty)
let (balance) = _balance.read(owner, target_material)
_balance.write(owner, target_material, balance + qty)
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - qty)
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + qty)
_setMaterialByOwner(owner, target_material, 0)
_maybeUnsetMaterialByOwner(owner, source_material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, source_material, qty)
TransferSingle.emit(__addr, 0, owner, target_material, qty)
return ()
end

The following test(s) can be added to tests/briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_mutate_ft_material_zero(briq_contract):
# Mint 100 fungible tokens of material `1` to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=100))
# Mutate 10 of the tokens to a new material with id zero
await invoke_briq(briq_contract.mutateFT(owner=ADDRESS, source_material=1, target_material=0, qty=10))
# Get the balance of `ADDRESS` for material with id zero
balanceMaterialZero = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=0).call()).result.balance
assert balanceMaterialZero == 10

Recommendation

Assert that the argument target_material in the function mutateFT_(...) cannot be zero.

6.4.3 Non-fungible Briq tokens can be mutated to have a token_id of zero

In the function mutateOneNFT_(...) after briq_token_id has been calculated for the second time there is no check to ensure that the value is zero. The variable briq_token_id is calculated with the formula briq_token_id = uid * 2**64 + target_material which means that it is possible to set target_material and uid to values that satisfy target_material == (uid * 2**64) * -1 which will result in a briq_token_id of zero. The code is reproduced below:

@external
func mutateOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, uid: felt, new_uid: felt):
_onlyAdmin()
assert_lt_felt(uid, 2**188)
assert_lt_felt(new_uid, 2**188)
assert_not_zero(source_material - target_material)
# NFT conversion
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - 1)
let briq_token_id = uid * 2**64 + source_material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = owner
_owner.write(briq_token_id, 0)
_unsetTokenByOwner(owner, source_material, briq_token_id)
_maybeUnsetMaterialByOwner(owner, source_material) # Keep after unset token or it won't unset
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + 1)
# briq_token_id is not the new ID
let briq_token_id = new_uid * 2**64 + target_material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = 0
_owner.write(briq_token_id, owner)
_setMaterialByOwner(owner, target_material, 0)
_setTokenByOwner(owner, target_material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, uid * 2**64 + source_material, 1)
TransferSingle.emit(__addr, 0, owner, new_uid * 2**64 + target_material, 1)
Mutate.emit(owner, uid * 2**64 + source_material, new_uid * 2**64 + target_material, source_material,

,! target_material)

    return ()
end

The following test(s) can be added to briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_mutate_one_nft_token_id_zero(briq_contract):
# Values for the NFT before the mutation
beforeUid = 1
beforeMaterial = 1
beforeTokenId = beforeUid * 2**64 + beforeMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=ADDRESS, material=beforeMaterial, uid=beforeUid))
# The specific values needed to have a token id of zero after mutate
afterUid = 2
afterMaterial = -abs(2 * (2**64))
afterTokenId = afterUid * 2**64 + afterMaterial
# Mutate the NFT token
await invoke_briq(briq_contract.mutateOneNFT(owner=ADDRESS, source_material=beforeMaterial,

,! target_material=afterMaterial, uid=beforeUid, new_uid=afterUid))

# Get the owner of token id `0`
zeroTokenOwner = (await briq_contract.ownerOf(0).call()).result.owner
# Assert that the owner of the zero token is now assigned to an address
assert zeroTokenOwner == ADDRESS

Recommendation

The function must validate that both source_material and ‘target_material are within the range of 1 to 2ˆ64 - 1. Add a check to briq_token_id before writing to storage to ensure that the value is not zero.

6.4.4 No balance check on converting Briq tokens from fungible to non-fungible

The function convertOneToNFT_(...) does not ensure that the fungible token balance of owner is sufficient. This allows a non-fungible Briq token to be created even if owner has no fungible tokens of the given material. The process of reducing the fungible token balance for the owner whose balance is zero will also cause an overflow upon writing to _balance which will change their fungible token balance to STARKNET_PRIME - 1. The code is shown below:

@external
func convertOneToNFT_{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdmin()
assert_not_zero(owner)
assert_not_zero(material)
assert_lt_felt(uid, 2**188)
# NFT conversion
let token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(token_id)
assert curr_owner = 0
_owner.write(token_id, owner)
# No need to change material
_setTokenByOwner(owner, material, token_id, 0)
let (balance) = _balance.read(owner, material)
_balance.write(owner, material, balance - 1)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, material, 1)
TransferSingle.emit(__addr, 0, owner, token_id, 1)
ConvertToNFT.emit(owner, material, token_id)
return ()
end

The following test(s) can be added to briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_convert_ft_to_nft_no_balance(briq_contract):
# Convert immediately without minting any tokens
await invoke_briq(briq_contract.convertOneToNFT(owner=ADDRESS, material=1, uid=1))
# Account `ADDRESS` now has a balance issue so to confirm the NFT was created transfer it to observe the balance on

,! another account

await invoke_briq(briq_contract.transferOneNFT(sender=ADDRESS, recipient=OTHER_ADDRESS, material=1 ,

,! briq_token_id=1 * 2**64 + 1), ADDRESS)

# Get the balance of the address that received the newly created NFT
materialBalance = (await briq_contract.balanceOfMaterial(owner=OTHER_ADDRESS, material=1).call()).result.balance
# Get the balance of fungible tokens owned by `ADDRESS`
fungibleBalance = (await briq_contract.balanceDetailsOfMaterial_(owner=ADDRESS,

,! material=1).call()).result.ft_balance

# Balance of `ADDRESS` is now a very large value
assert fungibleBalance == 3618502788666131213697322783095070105623107215331596699973092056135872020480
# The NFT has successfully been transferred to another address
assert materialBalance == 1

Recommendation

Ensure that the fungible token balance for owner is enough to convert a fungible token into a non-fungible token.

6.4.5 Missing input validation in convertOneToNFT_(...)

The parameters material and uid are not checked for range and validity. There are also no checks for overflow. The code is presented below.

@external
func convertOneToNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdmin()
assert_not_zero(owner)
assert_not_zero(material)
assert_lt_felt(uid, 2**188)
# NFT conversion
let token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(token_id)
assert curr_owner = 0
_owner.write(token_id, owner)
# No need to change material
_setTokenByOwner(owner, material, token_id, 0)
let (balance) = _balance.read(owner, material)
_balance.write(owner, material, balance - 1)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, material, 1)
TransferSingle.emit(__addr, 0, owner, token_id, 1)
ConvertToNFT.emit(owner, material, token_id)
return ()
end

Recommendation

Check material and uid for range and validity. Check for overflow. In case of error, revert.

6.4.6 New uid can be same as existing uid when mutating non-fungible Briq tokens

On L78 there is a comment that states that new_uid should be different to uid however this is not enforced in the function mutateOneNFT_(...) and it is possible to mutate a non-fungible Briq token to have a different material and the same uid. This has been set to an undetermined severity because the reason for changing the uid is that the UI can potentially conflict, however we do not know the full impact of conflicting uids on the front-end for the project. The following test(s) can be added to briq_impl_test.py to verify this behavior:

@pytest.mark.asyncio
async def test_mutate_one_nft_same_uid(briq_contract):
# Values for the NFT before the mutation
beforeUid = 1
beforeMaterial = 1
beforeTokenId = beforeUid * 2**64 + beforeMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=ADDRESS, material=beforeMaterial, uid=beforeUid))
# The specific values needed to have a token id of zero after mutate
afterUid = beforeUid
afterMaterial = 2
afterTokenId = afterUid * 2**64 + afterMaterial
# Mutate the NFT token
await invoke_briq(briq_contract.mutateOneNFT(owner=ADDRESS, source_material=beforeMaterial,

,! target_material=afterMaterial, uid=beforeUid, new_uid=afterUid))

# No asserts needed, if this test passes then the NFT token has successfully been mutated while having the same uid

Recommendation

Add a check to ensure that uid and new_uid are not the same.

Resolution

I think this is a broken comment, actually. The general behavior is that new_uid == uid, and that is expected to work. However, since there can be a token_id with target_material and new_uid already, there is an option to pass a new_uid different to uid. The comment is rather unclear, but this is all working. I’ve rephrased.

6.4.7 Unused imports in convert_mutate.cairo

FileFix commitTypeStatus
contracts/briq_erc1155_like/convert_mutate.cairo—InfoUnresolved

The following imports are not used in the file convert_mutate.cairo:

  • SignatureBuiltin
  • get_caller_address
  • assert_nn_le
  • assert_lt
  • assert_le
  • get_fp_and_pc
  • alloc

Recommendation

Remove the unused imports.

Resolution

Will clean up at a later stage.

6.4.8 Missing event emission in mutateFT_(...)

FileFix commitTypeStatus
contracts/briq_erc1155_like/convert_mutate.cairo—InfoAcknowledged

The function mutateFT_(...) does not emit a Mutate event like other mutate function mutateOneNFT_(...).

Recommendation

Add an event emission for calls to mutateFT_(...).

Resolution

This was on purpose, the tokens being fungible, mutation is equivalent to burning and minting a corresponding amount (whereas we want to track NFTs, potentially). Having a dedicated event could still be useful, I’ll consider it.

6.5 contracts/briq_erc1155_like/transferability.cairo

6.5.1 Missing input validation in transferOneNFT_(...)

The function transferOneNFT_(...) does not validate the input parameters recipient, material, and briq_token_id. The input parameters material and briq_token_id are not checked to be within a valid range. The recipient is not checked for address(0x0). The code is reproduced below.

@external
func transferOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, material: felt, briq_token_id: felt):
_onlySetAnd(sender)
assert_not_zero(sender)
assert_not_zero(material)
assert_not_zero(briq_token_id)
let (curr_owner) = _owner.read(briq_token_id)
assert sender = curr_owner
_owner.write(briq_token_id, recipient)
# Unset before setting, so that self-transfers work.
_unsetTokenByOwner(sender, material, briq_token_id)
_setTokenByOwner(recipient, material, briq_token_id, 0)
_maybeUnsetMaterialByOwner(sender, material) # Keep after unset token or it won't unset
_setTokenByOwner(recipient, material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, sender, recipient, briq_token_id, 1)
return ()
end

Recommendation

The function must check recipient for address(0x0). It must also assure that material and briq_token_id are valid identifiers.

Resolution

Asserted recipient and material / briq_token_id accordingly.

6.5.2 Missing events emission in transferability.cairo

FileFix commitTypeStatus
contracts/briq_erc1155_like/transferability.cairo—LowAcknowledged

The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions that should emit events is presented below.

func setSetAddress_(...)
func transferFT_(...)

Recommendation

Consider emitting events for the functions listed above.

Resolution

SetSetAddress should, the rest are reconstructed from Transfer().

6.5.3 Missing input validation in setSetAddress_(...)

FileFix commitTypeStatus
contracts/briq_erc1155_like/transferability.cairo—LowUnresolved

The function setSetAddress_(...) does not validate the input parameter address. Although the function can only be called by the admin, the function can be more robust. Users also need protection from admin actions. Moreover, the function also does not emit an event. The code is reproduced below:

@external
func setSetAddress_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (address: felt):
_onlyAdmin()
_set_backend_address.write(address)
return ()
end

Recommendation

The function must assert that the input parameter address is different from address(0x0). The function should also emit an event.

Resolution

Similar class of problem to other privileged functions. Not entirely sure how to proceed at the moment.

6.5.4 Missing overflow checks in transferFT_(...)

The function transferFT_(...) does not explicitly check for overflows when updating the senders and receivers balance. The code is reproduced below:

@external
func transferFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, material: felt, qty: felt):
_onlySetAnd(sender)
assert_not_zero(sender)
assert_not_zero(material)
assert_not_zero(qty)
# FT conversion
let briq_token_id = material
let (balance_sender) = _balance.read(sender, briq_token_id)
assert_le_felt(qty, balance_sender)
_balance.write(sender, briq_token_id, balance_sender - qty)
let (balance) = _balance.read(recipient, briq_token_id)
_balance.write(recipient, briq_token_id, balance + qty)
_setMaterialByOwner(recipient, material, 0)
_maybeUnsetMaterialByOwner(sender, material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, sender, recipient, briq_token_id, qty)
return ()
end

Recommendation

Check for overflows before writing to _balance for both the sender and receiver.

Resolution

Added check. Interestingly, balanceOf_’s result can overflow from too many FT and NFT at once. I suppose I can’t really fix that too easily here.

6.5.5 Briq token transfers can have the same sender and receiver

The functions transferFT_(...) and transferOneNFT_(...) allow the sender and receiver address to be the same. Currently this doesn’t introduce any bugs, however given that this protocol is still under development any changes may create bugs in the future.

Recommendation

During the discussion between the Nethermind and Briq teams it was mentioned that self transfers are not necessary for the protocol and do not benefit the user in any way. Since self transfers are not necessary for the protocol it is recommended to remove this feature as any changes to the protocol may introduce bugs related to self transfers in the future.

Resolution

Asserted against.

6.5.6 Unused imports in transferability.cairo

FileFix commitTypeStatus
contracts/briq_erc1155_like/transferability.cairo—InfoUnresolved

The following imports are not used in the file transferability.cairo:

  • assert_nn_le
  • assert_lt
  • assert_lt_felt
  • get_fp_and_pc
  • alloc

Recommendation

Remove the unused imports.

Resolution

Planning to do a cleanup pass.

6.6 contracts/library_erc721/transferability_enum.cairo

6.6.1 Missing input validation in transferFrom_(...)

The function transferFrom_(...) does not check if the token_id is within a valid range, the sender and the recipient for address(0x0). It also does not check if sender is different from recipient. The function is reproduced below.

@external
func transferFrom_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, token_id: felt):
ERC721_approvals._onlyApproved(sender, token_id)
ERC721_lib_transfer._transfer(sender, recipient, token_id)
# Unset before setting, so that self-transfers work.
ERC721_enumerability._unsetTokenByOwner(sender, token_id)
ERC721_enumerability._setTokenByOwner(recipient, token_id, 0)
return ()
end

Recommendation

Validate the token_id, sender, and recipient.

Resolution

Added checks in the called _transfer function.

6.6.2 Incorrect namespace title

The namespace title ERC271_transferability appears to be a spelled incorrectly, it should be ERC721_transferability. This issue extends into contracts/set_impl.cairo on L27 and L55 where the import also uses the same spelling error.

Recommendation

Rename the namespace to ERC721_transferability and reflect these changes in contracts/set_impl.cairo

6.7 contracts/set_impl.cairo

6.7.1 Functions with view visibility making changes to state

FileFix commitTypeStatus
contracts/set_impl.cairo89fdd2dInfoFixed

The functions assemble(...), disassemble(...) and transferOneNFT(...) use the @view decorator. However, these functions make state changes.

Recommendation

Change the decorators for assemble(...), disassemble(...) and transferOneNFT(...) to use the @external decorator.

Resolution

Changed to external.

6.8 contracts/briq_impl.cairo

6.8.1 Unused implicit arguments

FileFix commitTypeStatus
contracts/briq_impl.cairo—InfoUnresolved

The functions balanceOf_(...), balanceDetailsOf_(...), multiBalanceOf_(...), totalSupply_(...) use the implicit argument bitwise_ptr which is unused by all functions. The relevant functions are shown below: disa

Recommendation

Remove the implicit argument bitwise_ptr from the relevant functions.

Resolution

I think I’ve added them to some of these because called functions use it and it avoids having to set local pointers. I also think that cairo-lang itself might evolve to make these redundant. Will consider in the future a cleanup here.

6.9 contracts/upgrades/proxy.cairo

6.9.1 No event emitted and missing input validation in proxy.constructor(...)

FileFix commitTypeStatus
contracts/upgrades/proxy.cairo4f03d9cInfoFixed

The proxy.constructor(...) does not emit any event. However, it performs important state changes: a) define the admin of the application; b) set the implementation address. The admin and the implementation_address are not checked for address(0x0). The code is shown below.

func constructor{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
}(admin: felt, implementation_address: felt):
Proxy_initializer(admin)
Proxy_set_implementation(implementation_address)
return ()
end

Recommendation

Emit an event in the proxy.constructor(...) containing admin and the implementation_address. This event will be important to check that addresses have been set accordingly. Check admin and implementation_address for address(0x0).

Resolution

Done on my end of the contracts. Ideally, Open Zeppelin will change their code on that side.

6.10 contracts/upgrades/upgradable_mixin.cairo

6.10.1 No event emitted when updating RootAdmin

FileFix commitTypeStatus
contracts/upgrades/upgradable_mixin.cairo4f03d9cLowFixed

The function upgradable_mixin.setRootAdmin_(...) does not emit any event. It calls the function library.Proxy_set_admin(...), which also does emit any event. Both functions do not check the new_admin for address(0x0). The code of both functions are presented below.

func upgradable_mixin.setRootAdmin_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (new_admin: felt):
_onlyAdmin()
Proxy_set_admin(new_admin)
return ()
end
func library.Proxy_set_admin{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
}(new_admin: felt):
Proxy_admin.write(new_admin)
return ()
end

Recommendation

Emit an event in library.Proxy_set_admin(...) containing the new_admin. Check the new_admin of both functions for address(0x0). If the check is true, revert.

Resolution

Done on my end of the contracts. Ideally, Open Zeppelin will change their code on that side.

6.11 contracts/library_erc721/approvals.cairo

6.11.1 Functions missing events emission in approvals.cairo

FileFix commitTypeStatus
contracts/library_erc721/approvals.cairo—LowUnresolved

The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions not emitting events is presented below.

func approve_(...)
func setApprovalForAll_(...)

Recommendation

Emit events for the functions listed above.

Resolution

Need to be added, as those are defined in ERC721 too.

6.12 contracts/library_erc721/transferability_library.cairo

6.12.1 Not checking for overflow in _transfer(...)

The function _transfer(...) does not check if balance has overflowed before writing to storage variable _balance for both the sender and recipient. The code is reproduced below:

func _transfer{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, token_id: felt):
# Reset approval (0 cost if was 0 before on starknet I believe)
ERC721_approvals.approve_nocheck_(0, token_id)
let (curr_owner) = _owner.read(token_id)
assert sender = curr_owner
_owner.write(token_id, recipient)
let (balance) = _balance.read(sender)
_balance.write(sender, balance - 1)
let (balance) = _balance.read(recipient)
_balance.write(recipient, balance + 1)
_onTransfer(sender, recipient, token_id)
return ()
end

Recommendation

Check for overflows on balance before writing to storage variable _balance.

Resolution

Overflow check added.

6.13 contracts/set_erc721/token_uri.cairo

6.13.1 Test function implemented inside core contract

FileFix commitTypeStatus
contracts/set_erc721/token_uri.cairo—LowUnresolved

The function setTokenURI_(...) has a comment stating that the function should be used for testing only. It is generally recommended to separate smart contract code used exclusively in testing from core protocol smart contract code. The function is reproduced below:

## Testing only
@external
func setTokenURI_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
bitwise_ptr: BitwiseBuiltin*,
range_check_ptr
} (token_id: felt, uri_len: felt, uri: felt*):
alloc_locals
_onlyAdmin()
# TODO: is this useless?
let (owner) = _owner.read(token_id)
assert_not_zero(owner)
_setTokenURI(0, token_id, uri_len, uri)
URI.emit(uri_len, uri, token_id)
return()
end

Recommendation

Move setTokenURI_ to a separate contract which imports set_impl.cairo to create a separation of concerns between testing code and protocol code.

Resolution

Planned but not fixed yet. Only admins can use it also mitigates the problem.

6.13.2 Not using boolean type of value fixed to 0 or 1

FileFix commitTypeStatus
contracts/set_erc721/token_uri.cairo402976aInfoFixed

The function _setTokenURI is an internal function and is only called with may_use_special_token_mode set to 0 or 1. However this is not asserted inside _setTokenURI. If may_use_special_token_mode is at some point in the future determined non-deterministically this would allow uri_len * may_use_special_token_mode == 2 condition to pass with an invalid uri array. The function is reproduced below:

func _setTokenURI{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
bitwise_ptr: BitwiseBuiltin*,
range_check_ptr
} (may_use_special_token_mode: felt, token_id: felt, uri_len: felt, uri: felt*):
assert_not_zero(uri_len)
assert_lt_felt(uri[0], 2**249)
# This is 0 or 1
if uri_len * may_use_special_token_mode == 2:
let (rem) = bitwise_and(uri[1], 2**59 - 1)
if uri[1] == rem:
# The rest has already been written in the token-id
# Flag it with both special bits for continuation and 'part of token_id'.
_token_uri.write(token_id, uri[0] * 4 + 3)
return ()
end
# Write the first URI with the special continuation LSB
_token_uri.write(token_id, uri[0] * 4 + 1)
_setExtraTokenURI(token_id, uri_len - 2, 0, uri + 1)
# event_uri.emit(token_id, uri_len, uri)
else:
if uri_len == 1:
# Just write the URI normally.
_token_uri.write(token_id, uri[0] * 4)
return ()
end
# Write the first URI with the special continuation LSB
_token_uri.write(token_id, uri[0] * 4 + 1)
_setExtraTokenURI(token_id, uri_len - 2, 0, uri + 1)
# event_uri.emit(token_id, uri_len, uri)
end
return()
end

Recommendation

To improve maintainability, there should be a check to assert that may_use_special_token_mode is a boolean value (either 0 or 1). Using the Cairo bool library is also recommended to improve readability.

Resolution

Fixed as recommended.

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

We recommend the following improvements be made to the documentation of this project:

  • Inline comments to describe each function (what it does, inputs, outputs).
  • Inline comments for lines of code that could benefit from an added description for further context.
  • Formalize the functional requirements of the project, and continue to update these requirements as the project is developed.

The test suite is reduced and validates the behavior of the application if users behave as expected. Several edge cases are not handled. Unit Testing is the testing phase where each unit in the system is individually tested. The goal is to isolate each part of the system to ensure they are working as specified. The developer must consider the requirements of each function and make sure that the input/output parameters are in range. In this sense, the system’s technical specification plays an important role in creating good test cases, delimiting the scenarios for using a function, and which situations should be avoided by each function. It is critical that the test suite be created very carefully to reduce the risk of exploits, handling edge cases, and making sure that inputs and outputs of functions are in valid ranges and that overflow has not happened.

On the other hand, systemic tests validate the integration between the various modules of the system in an production-like environment. The system must be robust enough to deal with users interacting with it in unplanned ways, such as calling functions in a different order than expected, passing wrong input values, and even trying to hack the system.

Our analysis of the code indicates that many parameters are not properly validated. It is essential to assure that each input parameter has a valid range, the user calling the function has the proper privilege, inside the function check for overflows, and making sure that the output is also in valid range. In view of this, our recommendation is to considerably expand the test suite, as well as improve the technical documentation

of the project, with special attention to edge cases.

During the re-audit phase Cairo 0.9.0 had been released, which introduced breaking changes to smart contracts written in Cairo 0.8.0. Because there is no upper limit for the cairo-lang version in requirements.txt the new version of cairo-lang is used to compile the contracts which causes them to fail compilation and testing. In order to run the tests correctly, line 3 was changed to cairo-lang>=0.8.1,<0.9 and requirements had to be reinstalled.

Test Suite Provided (Initial Review and Final Review)

,! 'asyncio_mode' default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or,! 'asyncio_mode=auto' in pytest configuration file.

,! the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will,! stop working

,! default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or,! 'asyncio_mode=auto' in pytest configuration file.

,! ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop,! working

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.