Dojo
Game Engine

Dojo is a provable game engine for building on-chain games on Starknet. We reviewed the World contract that registers entities, stores their data and controls who can change it.
report id
0159
category
Infra & Wallets
language
Cairo
final report
February 7, 2024
lines of code
945
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind for the Dojo Game Engine. Dojo is a provable game engine and toolchain for building on-chain games and autonomous worlds. It is built around the concept of Entity Component System architecture. This model revolves around systems acting on entities, which are collections of pure data components. Systems efficiently determine which entities to process based on persistent queries over these components. The world contract controls all these components (systems and models). This contract enables the registration, creation, and deletion of entities. All data of these entities is stored in an on-chain database that supports indexing. The world contract also includes access control logic to authorize which addresses and systems can create, delete, or update entities.

The audited code comprises 945 lines of code in Cairo. The Dojo team has provided comprehensive documentation that explains Dojo’s core architecture, and the detailed properties of each component, as well as how they interact with each other.

The audit was performed using: (a) manual analysis of the codebase and (b) simulation of the smart contracts.

Audit assessment
Audit TypeSecurity Review
Initial ReportJan 25, 2024
Final ReportFeb 7, 2024
MethodsManual Review
Repositorydojo-core
Commit Hash36e5853877
Final Commit Hash1a1f348536
DocumentationDojo Book
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
25
Fixed
22
Acknowledged
3
Mitigated
0
Unresolved
0

Findings by severity

  • Critical2
  • High2
  • Medium5
  • Low0
  • Informational11
  • Best Practices5

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/world.cairo36822260.3%82672
2src/components.cairo100.0%01
3src/database.cairo781519.2%10103
4src/base.cairo24833.3%840
5src/packing.cairo128129.4%17157
6src/executor.cairo261557.7%647
7src/lib.cairo14750.0%324
8src/model.cairo1218.3%114
9src/database/utils.cairo944851.1%24166
10src/database/storage.cairo5900.0%1271
11src/database/index.cairo1012423.8%29154
12src/components/upgradeable.cairo40717.5%956
Total94535938.0%2011505

3

Summary of Issues

#FindingSeverityUpdate
1Anyone can take ownership of non-exist modelsCriticalFixed
2Setting metadata for resource can overwrite another resources metadataCriticalFixed
3Executor contract can be upgraded to any class hashHighFixed
4Function delete(...) does not update the new position for the last elementHighFixed
5Incorrect check in the get_many() function results in missing return dataMediumFixed
6Incorrect check in the function metadata_uri() cause infinite loopMediumFixed
7Infinite loop in query(...) function when the condition is specifiedMediumFixed
8Packing lying on untrusted inputMediumAcknowledged
9The writer is able to upgrade a contractMediumFixed
10Function get_by_key(...) cannot be used because specific keys are not set anywhereInfoFixed
11Missing check for duplicated elements in ids input params in the function find_matching(...)InfoFixed
12No check if layout element matches max felt sizeInfoFixed
13Open TODOsInfoFixed
14Potential for front-running and DOS (Denial of Service) in register_model(...)InfoAcknowledged
15Potential overflow offset in the function get_many(...)InfoFixed
16Power of a value missed edge caseInfoFixed
17The function find_matching(...) will fail for empty arraysInfoFixed
18The index is not set in set_entity(...)InfoFixed
19Upgrade checks not enoughInfoFixed
20WhereCondition is never being used in the function query(...)InfoFixed
21Inconsistency of setting boolean valuesBest PracticesFixed
22Incorrect documentation/commentsBest PracticesFixed
23Missing checks for a new executor contractBest PracticesFixed
24Unnecessary check of address zeroBest PracticesAcknowledged
25Unused variablesBest PracticesFixed

4

System Overview

Dojo is a provable game engine for onchain games on Starknet and autonomous worlds. The game’s owner deploys a world contract, which behaves as a database. It stores world models and systems. The world contract is a core contract that allows users to register their models, deploy system contracts, or set metadata for models.

The resource owners deploy system contracts that hold the world’s logic, or it is possible to say game logic. The best way to understand this is an example: Imagine a system contract as a movement functionality for the world. It will hold functions that will update the player’s position in the world.

Another component of this protocol is the model. A model is a structure that is represented as a table. It holds keys and values, which are stored in the world contract. First, an owner of a model needs to declare a class of a specific model to be able to register it within the World contract.

The protocol contains two main contracts: World and Executor. Code is organized into separate files, which we call modules or libraries. The main libraries of World contract are:

Fig. 2 presents the interaction diagram of the contracts.

The Database module contains the logic of a relational database. Users can create tables with keys and values, with each table representing an entity in the world contract.

The Index module handles creating and deleting indexes for the pair table-key.

The Storage module works as the storage of world contract. It offers low-level functionality for storing and fetching data from the internal storage of the contract.

The Packing module enables packing and unpacking functionality for custom data structures, ensuring efficient data handling within the system.

The modules mentioned above are part of the World contract, which implements an additional access control layer and external functionality for associating classes of models with the World contract and deploying system contracts. Furthermore, it allows functionality to write into a database and obtain needed data.

Another contract of the protocol is the Executor. Executor provides library system calls to deployed classes. In the current implementation, the Executor is called from World contract to obtain the name of the module class.

Two types of actors will interact with the World contract are:

a) Resource owners: Users who register models or deploy system contracts associated with the World contract become resource owners. They have the authority to manage these resources by inserting data and metadata related to them. Additionally, resource owners can assign ownership or writing privileges to other account contracts for their resources. It’s important to note that the admin of the World contract is also part of this group.

b) Writers: Members of this group, likely system contracts, are responsible for setting data to the relational database or deleting data.

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 Anyone can take ownership of non-exist models

FileFix commitTypeStatus
world.cairobfd952b
202d077
0e1ea82
1a1f348
CriticalFixed

The registering model process has no access control checks if the model name does not exist. However, owners of models are stored in the same mapping. A malicious actor can register their own model to take ownership of existing contracts or anything like the following assumption.

If there is a contract deployed by calling the deploy_contract(...) method, the owner will be the caller. However, a malicious actor can register the model with the name as the contract address of this newly deployed contract to take ownership.

Deploying a contract does not write models storage its contract address. So following if statement will grant ownership to the malicious actor;

fn register_model(ref self: ContractState, class_hash: ClassHash) {
// ...
let current_class_hash = self.models.read(name);
if current_class_hash.is_non_zero() {
assert(self.is_owner(caller, name), 'only owner can update');
prev_class_hash = current_class_hash;
} else {
self.owners.write((name, caller), true);
};

// @audit-issue: Everyone can make themselves of owner of anything that doesn't exist in models.

self.models.write(name, class_hash);
EventEmitter::emit(ref self, ModelRegistered { name, class_hash, prev_class_hash });
}

As we see there is no model storage writing on the deploy_contract(...) method.

fn deploy_contract(
ref self: ContractState, salt: felt252, class_hash: ClassHash
) -> ContractAddress {
let (contract_address, _) = deploy_syscall(
self.contract_base.read(), salt, array![].span(), false
)
.unwrap_syscall();
let upgradeable_dispatcher = IUpgradeableDispatcher { contract_address };
upgradeable_dispatcher.upgrade(class_hash);

self.owners.write((contract_address.into(), get_caller_address()), true);

EventEmitter::emit(
ref self, ContractDeployed { salt, class_hash, address: contract_address }
);

contract_address
}

So initially, the model mapping will be zero for newly deployed contracts, and malicious actors can register the model to get ownership and then get access to access-controlled methods.

Recommendation

Consider changing the owner storage structure or registering the deployed contract address as a model.

Resolution

In the commit bfd952b5112f3790621b1a5f68d47b25d9daa7d2 a new storage variable was added to avoid such conflict.

Update from Nethermind Security

It is still feasible to get an ownership of WORLD.

Update from the client

Fixed in 202d077 and missing test added in 0e1ea82. Updated in 1a1f3485 to ensure the resource metadata are also protected and only controlled by the world’s creator.

6.2 Setting metadata for resource can overwrite another resources metadata

FileFix commitTypeStatus
world.cairof129edfCriticalFixed

Resource metadata stored in one storage mapping like

#[storage]
struct Storage {
// ...
metadata_uri: LegacyMap::<felt252, felt252>,
// ...
}

Where the felt value is the name of the resource, and the first mapped value is the length of the metadata array. Length is used to read metadata like the following.

fn metadata_uri(self: @ContractState, resource: felt252) -> Span<felt252> {
let mut uri = array![];

// We add one here since we start i at 1;
let len = self.metadata_uri.read(resource) + 1;

let mut i = resource + 1;
loop {
if len == i {
break;
}

uri.append(self.metadata_uri.read(i));
i += 1;
};

uri.span()
}

However, writing can be done by only the owner of the resource;

fn set_metadata_uri(ref self: ContractState, resource: felt252, mut uri: Span<felt252>) {
assert(self.is_owner(get_caller_address(), resource), 'not owner');
// ...
}

But everyone can register their own model and be their own model’s owner by calling register_model(...). If a malicious actor registers a model with the name felt of target_resource - 1, then the actor can use this ownership to overwrite target resources metadata.

Recommendation

Consider changing metadata storing structure. Use Resource -> Span mapping.

Resolution

That’s a good catch. The situation here originates from the metadata uri being handles as a resource, but on more than one felt. Resources are to be considered as a one felt long identifier. To address this, we’ve adjusted the way metadata are handled by the world, and now it follows the regular ACL flow by using the same logic as models do. commit: f129edfc.

6.3 Executor contract can be upgraded to any class hash

FileFix commitTypeStatus
world.cairo479197e
04f7ef7
HighFixed

Function register_model(...) can be used to upgrade existing executor contract implementation. In this function, there is an external call to the executor, where the executor library calls to target class hash. However, a malicious actor can pass any class hash. That class hash can contain replace_class_syscall to upgrade the executor contract to any other class hash.

fn register_model(ref self: ContractState, class_hash: ClassHash) {
// ...
let name = *class_call(@self, class_hash, NAME_ENTRYPOINT, calldata.span())[0];
// @audit-issue: Any class hash can be used to library call at executor.
// ...
}
impl Executor of IExecutor<ContractState> {
fn call(
self: @ContractState,
class_hash: ClassHash,
entrypoint: felt252,
calldata: Span<felt252>
) -> Span<felt252> {
starknet::syscalls::library_call_syscall(class_hash, entrypoint, calldata)
.unwrap_syscall() // @audit-issue: There are no checks, call forwarded directly.
}
}

Recommendation

Consider deploying the contract, then call to get the name.

Resolution

To limit the API changes on current Dojo implementation, we propose in commits 479197e4f and 04f7ef756 to remove the executor. Indeed, the library_call syscall can’t prevent the execution of syscalls, and in the context of Dojo, we do need model registering to be permissionless. The proposed solution introduces communication with models via regular contract_call syscall instead of library call, which prevents the world (or auxiliary contract like executor) from being modified.

6.4 Function delete(...) does not update the new position for the last element

FileFix commitTypeStatus
index.cairoe95153cHighFixed

In the index.cairo contract, there are 3 mappings used to store elements.

1. The first mapping stores the position of an element (index, id) => position + 1; 2. The second mapping stores the number of elements in this index (index) => length; 3. The third mapping stores the id of the element in each position (index, position) => id;

When an element is removed from an index, the function delete(...) does the following:

  • Removes the position of the deleted element from the first mapping by setting its value to 0;
  • Decreases the number of elements in the index in the second mapping;
  • Updating the third mapping to point to the last element id;

However, since the last element is moved to a new position, the position of the last element is also changed. This means that we also need to update the first mapping for the last element. Currently, the function delete(...) does not handle this, which breaks the structure of the contract as the first mapping points to the wrong position.

fn delete(address_domain: u32, index: felt252, id: felt252) {
if !exists(address_domain, index, id) {
return ();
}

let index_len_key = build_index_len_key(index);
let replace_item_idx = storage::get(address_domain, index_len_key) - 1;

let index_item_key = build_index_item_key(index, id);
let delete_item_idx = storage::get(address_domain, index_item_key) - 1;

storage::set(address_domain, index_item_key, 0);
storage::set(address_domain, index_len_key, replace_item_idx);

// Replace the deleted element with the last element.
// NOTE: We leave the last element set as to not produce an unncessary state diff.

// @audit-issue Not update new position of replace item
let replace_item_value = storage::get(address_domain, build_index_key(index, replace_item_idx));
storage::set(address_domain, build_index_key(index, delete_item_idx), replace_item_value);
}

Recommendation

Consider updating the new position for the last element.

storage::set(address_domain, build_index_item_key(index, replace_item_value), delete_item_idx + 1);

Resolution

Related to index removed code in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.

6.5 Incorrect check in the get_many() function results in missing return data

FileFix commitTypeStatus
storage.cairof03cce8
4b5c0f8
MediumFixed

The get_many(...) function uses offset to specify the starting position for retrieval from storage. It should retrieve storage slots from offset to offset + length - 1. However, the current code retrieves from offset to length - 1 only. If offset > length, it causes an infinite loop. The issue is evident in the code snippet below, where the loop breaks when offset == length.

let mut offset = offset;
loop {
// @audit-issue Incorrect check, should be (length + original_offset == offset.into())
if length == offset.into() {
break ();
}

Recommendation

Consider changing the break condition to length + original_offset == offset.into() where the original_offset is the initial value of offset before the loop starts.

Resolution

Yes that’s correct. Currently only the offset 0 is enforced by the dojo-lang macro. This is the reason why it wasn’t detected before.

We’ve adjusted the storage layer to always start at the offset 0, and offset is no longer exposed.

commit: f03cce87ade45848b5c5ab9b4a6cf72666343211.

And in a second commit, adjustement to be backward compatible without storing the length in the storage: 4b5c0f8023357a8d3c9c782ae89621b2978947ad.

We may update this to add the offset again to allow some further optimization on data retrieval. If added, it bounds checking will come along the offset.

6.6 Incorrect check in the function metadata_uri() cause infinite loop

FileFix commitTypeStatus
world.cairo—MediumFixed

In world.cairo, the metadata URI of a resource is stored as follows. First, at the resource position, it will store the length of the metadata URI. The following positions store the actual metadata URI.

fn metadata_uri(self: @ContractState, resource: felt252) -> Span<felt252> {
let mut uri = array![];

// We add one here since we start i at 1;
let len = self.metadata_uri.read(resource) + 1;

let mut i = resource + 1;
loop {
// @audit Incorrect check, it is assuming resource = 0
// @audit The check should be `if resource + len == i`
if len == i {
break;
}

uri.append(self.metadata_uri.read(i));
i += 1;
};

uri.span()
}

Consider the following scenario:

1. Alice stores the metadata URI for resource = 256 with a length of 5. In set_metadata_uri(...), it will set metadata_uri[256] = 5, and the next 5 positions from 257 to 261 will store the metadata URI; 2. Now, when the function metadata_uri(...) is called to get the metadata URI for resource = 256, it will calculate:;

len = metadata_uri[256] + 1 = 6
i = resource + 1 = 257

As you can see, since the starting value of i = 257 is already larger than len = 6, the break condition len == i will never be reached as the value of i will increase in each iteration.

Recommendation

Change the check to resource + metadata_uri[resource] == i.

Resolution

Concern addressed in the previous one as this code is not longer present.

6.7 Infinite loop in query(...) function when the condition is specified

FileFix commitTypeStatus
index.cairo98ed168MediumFixed

The query(...) function serves to return all elements from a table. This function allows the usage of the where parameter, which works similarly to the SQL where keyword, as it will return elements based on the condition. If this parameter is not specified, the function will return all values from the table.

However, only the elements that match the condition should be returned if the where parameter is used. This part of the code contains a loop that iterates through elements connected with a specific index. The index is created based on the key of the condition. The loop is where the issue arises, as the variable idx is not updated at the end of the iteration, which will cause an infinite loop, and the function will fail for an out of gas error.

Option::Some(clause) => {
let mut serialized = ArrayTrait::new();
table.serialize(ref serialized);
clause.key.serialize(ref serialized);
let index = poseidon_hash_span(serialized.span());

let index_len_key = build_index_len_key(index);
let index_len = storage::get(address_domain, index_len_key);
let mut idx = 0;

loop {
if idx == index_len {
break ();
}
let id = storage::get(address_domain, build_index_key(index, idx));
res.append(id);
// @audit-issue idx is not updated
}
},

Recommendation

It is necessary to update the idx variable inside a loop at the end of the iteration.

Resolution

Linked to WhereClause.

Code related to index was removed for now as it will be reworked in the future:

commit: 98ed1689eabad628331789c82ac01fdb3ff7e173

6.8 Packing lying on untrusted input

FileFix commitTypeStatus
packing.cairo—MediumAcknowledged

Packing method trusting layout parameter for bitsizes of variables inside unpacked span. However, the layout parameter is not coming from a trusted source. It can be inputted as any inside set_entity(...) method.

fn pack(ref packed: Array<felt252>, ref unpacked: Span<felt252>, ref layout: Span<u8>) {
assert(unpacked.len() == layout.len(), 'mismatched input lens');
let mut packing: felt252 = 0x0;
let mut offset: u8 = 0x0;
loop {
match unpacked.pop_front() {
Option::Some(item) => {
pack_inner(item, *layout.pop_front().unwrap(), ref packing, ref offset, ref packed);
},
Option::None(_) => {
break;
}
};
};
packed.append(packing);
}

Recommendation

Consider store using native types. If the writer is trusted executable, consider packing off-chain.

Resolution

The explicit layout is currently something very controlled by the dojo-lang compiler, where expansion of macro auto-generate the layout to be sent. As mentioned, sending a transaction explicitely can result in corrupted data, but since ACLs are covering who can modify the data, the input is always considered as trusted.

Finally, this is also a flexible way to allow the user to send arbitrarily packed data.

6.9 The writer is able to upgrade a contract

FileFix commitTypeStatus
world.cairo1d65123MediumFixed

The protocol allows the contract deployment to be associated with the world contract by the function deploy_contract(...). When the contract is deployed, it updates a mapping owners so that the caller of this function becomes an owner of the deployed contract.

The contract associated with the world can also be upgraded by invoking upgrade_contract(...) function. The following function checks the permissions of a caller by the following line:

assert_can_write(@self, address.into(), get_caller_address());
...
fn assert_can_write(self: @ContractState, resource: felt252, caller: ContractAddress) {
assert(
IWorld::is_writer(self, resource, caller)
|| IWorld::is_owner(self, get_tx_info().unbox().account_contract_address, resource)
|| IWorld::is_owner(self, get_tx_info().unbox().account_contract_address, WORLD),
'not writer'
);
}

The function assert_can_write(...) checks if the caller is the owner of WORLD or the owner of the resource(in this case, an owner of the contract) or has writing permissions.

However, that is where the issue arises as just an owner of the contract or of the WORLD should be able to upgrade a contract. The writer should not have a privilege for this action.

Recommendation

Consider checking access control for the upgrade_contract(...) function.

Resolution

Fixed in 1d65123556f8b070ebd730647d4407befb1c92d8 where only ownership is check for upgrade.

6.10 Function get_by_key(...) cannot be used because specific keys are not set anywhere

FileFix commitTypeStatus
index.cairoe95153cInfoFixed

In the index.cairo contract, the get_by_key(...) function is designed to return all entries containing a specific key. The function utilizes build_index_specific_key_len(...) and build_index_specific_key(...) to create the specific keys and build the storage address. However, these keys are not set anywhere in the contract. As a result, the function will fail to return any results, rendering it unusable.

fn get_by_key(address_domain: u32, index: felt252, key: felt252) -> Array<felt252> {
let mut res = ArrayTrait::new();
let specific_len_key = build_index_specific_key_len(index, key); // @audit-issue Not set anywhere
let index_len = storage::get(address_domain, specific_len_key);

let mut idx = 0;

loop {
if idx == index_len {
break ();
}

let specific_key = build_index_specific_key(index, key, idx); // @audit-issue Not set anywhere
let id = storage::get(address_domain, specific_key);
res.append(id);

idx += 1;
};

res
}

Recommendation

Implement features to set specific keys for index.

Resolution

Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.

6.11 Missing check for duplicated elements in ids input params in the function find_matching(...)

FileFix commitTypeStatus
utils.cairoe95153cInfoFixed

The function find_matching(...) takes multiple entity lists as input parameters. It aims to find the set of entities present in all the provided lists. It does this by counting how many times each entity id occurs. If an id appears a number of times equal to the number of lists, it means the entity with this id exists in all lists. However, the function does not account for cases where a list contains duplicated entities. If any entity_ids list contains duplicate values, it would cause the count in ids_match to be incorrect, potentially returning an id that does not exist in all lists.

Recommendation

Consider checking for duplicate elements in each entity_ids list.

Resolution

Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.

6.12 No check if layout element matches max felt size

FileFix commitTypeStatus
packing.cairo29621f5InfoFixed

The pack_inner(...) function is packing a felt element. It takes several parameters. One of them is a size specifying the element’s size. This element is obtained from the layout array parameter of the pack(...) function.

The element must fit to felt252; however, due to the following line and comments, the maximum size allowed is 251.

// Cannot use all 252 bits because some bit arrangements (eg. 11111...11111) are not valid felt252 values.
// Thus only 251 bits are used. ^-252 times-^
// One could optimize by some conditional alligment mechanism, but it would be an at most 1/252 space-wise improvement.
let remaining_bits: u8 = (251 - packing_offset).into();

If not, the line above will overflow, and the packing will revert. But If the last element of the layout (size) is larger than 251 and lower than 256 (to fit u8 space), the pack_inner(...) will not revert. There is no direct impact from this missing edge case. Still, to keep the consistency of the code, there should be an assertion that the size is not larger than 251.

Recommendation

Consider additional checks that the size is not larger than the 251 value.

Resolution

Was addressed in 29621f526957d5a330d2dc5c52af24fa68621c42 to ensure good behavior if layout is not correct.

6.13 Open TODOs

FileFix commitTypeStatus
packing.cairob1e1aa8InfoFixed

There is an open TODO in the function unpack(...). According to the comment, the function should raise an error, but currently, it only exits the loop.

Option::None(_) => {
// TODO: Raise error
break;
}

Recommendation

Consider reviewing the intended behavior of this branch again.

Resolution

Changed for a comment in b1e1aa82fa542dc516fa94d0915e0a4ab825a25f.

6.14 Potential for front-running and DOS (Denial of Service) in register_model(...)

FileFix commitTypeStatus
world.cairo—InfoAcknowledged

The world contract includes multiple models, each tracked by its name. This name is retrieved from the model class hash during the registration of the model.

fn register_model(ref self: ContractState, class_hash: ClassHash) {
let caller = get_caller_address();
let calldata = ArrayTrait::new();

// @audit-issue Can front-run to register model with the same name
let name = *class_call(@self, class_hash, NAME_ENTRYPOINT, calldata.span())[0];
let mut prev_class_hash = starknet::class_hash::ClassHashZeroable::zero();

// If model is already registered, validate permission to update.
let current_class_hash = self.models.read(name);
if current_class_hash.is_non_zero() {
assert(self.is_owner(caller, name), 'only owner can update');
prev_class_hash = current_class_hash;
} else {
self.owners.write((name, caller), true);
};

self.models.write(name, class_hash);
EventEmitter::emit(ref self, ModelRegistered { name, class_hash, prev_class_hash });
}

However, since register_model(...) is a public function, an attacker could front-run and register a null or malicious model using the same name as the legitimate model registration transaction. Consequently, the legitimate model cannot be registered because its name already exists. The attacker could repeatedly do this to effectively block all model registrations.

Recommendation

Consider restricting the addresses that can register a new model or change the method of model tracking. For instance, use a combination of (name, caller_address) to mitigate the issue.

Resolution

This is inherent to how the permissionless registration of the models works in the world. Due to that, front-running is indeed possible, but per se not an issue as then the permissions are still controlled by the owner.

6.15 Potential overflow offset in the function get_many(...)

FileFix commitTypeStatus
storage.cairof03cce8InfoFixed

The get_many(...) function uses offset to specify the start position to get from storage. The function retrieves storage slots from offset to offset + length - 1. However, offset uses u8 while length uses usize. Therefore, if length > max(u8), offset may overflow.

fn get_many(address_domain: u32, keys: Span<felt252>, offset: u8, length: usize, mut layout: Span<u8>) -> Span<felt252> {
let base = starknet::storage_base_address_from_felt252(poseidon_hash_span(keys));
let mut packed = ArrayTrait::new();

let mut offset = offset;
loop {
// @audit-issue offset's datatype is smaller than `usize` and could overflow
if length == offset.into() {
break ();
}

packed
.append(
starknet::storage_read_syscall(
address_domain, starknet::storage_address_from_base_and_offset(base, offset)
)
.unwrap_syscall()
);

offset += 1;
};
...
}

Recommendation

Consider using the same data type for offset and length.

Resolution

Solved in f03cce87ade45848b5c5ab9b4a6cf72666343211 where the offset is no longer exposed.

If we re-introduce the offset, bounds checks will be implemented as mentioned here.

6.16 Power of a value missed edge case

FileFix commitTypeStatus
packing.cairo0c0a4ecInfoFixed

Method fpow(...) returns 1 if the second variable is zero. But there is no check for whether the first value is zero or not. In math, 0 power 0 should be undefined. In this case the method should return. But it returns 1 early because the second variable is zero.

fn fpow(x: u256, n: u8) -> u256 {
let y = x;
// @audit-issue: Should revert if x and n are zero.
if n == 0 {
return 1;
}
// ...
}

Recommendation

Consider checking if both parameters are zero or not.

Resolution

Updated in 0c0a4ec462bff2ed5f8de3a8c712fc785621603d.

6.17 The function find_matching(...) will fail for empty arrays

FileFix commitTypeStatus
utils.cairoe95153cInfoFixed

The function find_matching(...) in utils.cairo serves to find entities that match the same IDs across all supplied entities.

As this function is not used anywhere in world.cairo, we guess that this function will be used for some off-chain interaction. Therefore, this function should handle all edge cases and probably not fail in different cases than assert statements checks.

However, the following function will fail if the supplied arrays are empty due to the following line.

// we want to keep the ordering from the first entity IDs
let mut ids1: Span<felt252> = *(ids.pop_front().unwrap()); //@audit-issue here it will fail for zero arrays

Recommendation

Consider handling a case when the supplied params are empty arrays.

Resolution

Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.

6.18 The index is not set in set_entity(...)

FileFix commitTypeStatus
world.cairoe95153cInfoFixed

The world.cairo exposes two functions: set_entity(...) and delete_entity(...), for setting the model to the entity and deleting the model from the entity, respectively.

When the entity is set, the contract interacts with the storage to store data related to the model based on the keys.

All the values linked with keys are set to 0 during the entity’s deletion. Additionally, when the entity is deleted, its index is also removed from the storage. However, no index is created with the entity during the flow of set_entity(...) function.

Recommendation

Consider creating an index when setting an entity.

Resolution

Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.

6.19 Upgrade checks not enough

FileFix commitTypeStatus
components/upgradeable.cairo8ff011fInfoFixed

The upgrade method has a couple of checks, but it is not checking that the new class hash has the method world(...). If upgraded to a hash that this function doesn’t exist, then all further upgrade trials will revert, and it can’t be reversed.

fn upgrade(ref self: ComponentState<TContractState>, new_class_hash: ClassHash) {
// @audit-issue: The assertion below will revert if there is no world entrypoint in the new class.
assert(
self.get_contract().world().contract_address.is_non_zero(),
Errors::INVALID_WORLD_ADDRESS
);
assert(
get_caller_address() == self.get_contract().world().contract_address,
Errors::INVALID_CALLER
);
// ...
}

Recommendation

Consider checking methods used in assertions that also exist in the new implementation.

Resolution

Attempt to fix with a library_call_syscall, not sure about the point of doing that right now. I would say we can wait interfaces to be supported and standardized (SNIP). A first attempt to mitigate this risk was done in commit: 8ff011.

6.20 WhereCondition is never being used in the function query(...)

FileFix commitTypeStatus
database.cairo
index.cairo
98ed168InfoFixed

The function query(...) accommodates both conditional and non-conditional queries by allowing an input where: Option<WhereCondition>. However, this function is currently only used in the function scan_ids(...), which always inputs Option::None as the where parameter. Consequently, WhereCondition is never used, and the logic written for it is redundant.

Consider the test case below for the function scan(...) that tests the case where it uses WhereCondition. This test fails and throws an Index out of bounds error.

#[test]
#[available_gas(10000000)]
fn test_database_scan2() {
let even = array![2, 4].span();
let odd = array![1, 3].span();
let layout = array![251, 251].span();

set_with_index('table', 'even', 0, even, layout);
set_with_index('table', 'odd', 0, odd, layout);

let condition : WhereCondition = WhereCondition {
key: 'odd', // Replace with an appropriate key
value: '1', // Replace with an appropriate value
};

let (keys, values) = scan('table', Option::Some((condition)), 2, layout);
let res = *keys.at(0);
res.print();

}

Recommendation

Review the logic around WhereCondition in the function query(...). If it’s no longer being used, consider removing it.

Resolution

The WhereClause was deprecated in 98ed1689eabad628331789c82ac01fdb3ff7e173.

6.21 Inconsistency of setting boolean values

FileFix commitTypeStatus
world.cairofdebe59Best PracticesFixed

The approach for setting a boolean value is differentiated across functions revoke_owner(...) and revoke_write(...). The first function applies the following line:

self.owners.write((resource, address), bool::False(()));

While the second one uses simple false:

self.writers.write((model, system), false);

In practice, there is no distinction. However, adhering to consistent coding practices is advisable.

Recommendation

Standardize the approach for setting boolean values.

Resolution

Updated in fdebe59d0997811b763d3059467fcb1d20b1a987.

6.22 Incorrect documentation/comments

FileFix commitTypeStatus
world.cairoef92799Best PracticesFixed

Documentation for functions and contracts plays a crucial role in providing clarity on expected behaviour and the parameters required for utilizing specific functionality. Accurate comments (inline documentation) are essential for facilitating a clear understanding for developers, auditors, and users.

The inline documentation is wrongly written for the following functions:

  • set_entity(...);
  • delete_entity(...);
  • entity(...);
  • entities(...);
  • entity_ids(...);
  • upgrade_contract(...);
  • deploy_contract(...);
  • set_metadata_uri(...);
  • metadata_uri(...);

Recommendation

Consider changing the documentation to describe the correct implementation of the functions.

Resolution

Documentation updated in ef9279995afd379cb13f7dabb2b8c6912b9b8690 with error refactoring.

6.23 Missing checks for a new executor contract

FileFix commitTypeStatus
world.cairoc804b77Best PracticesFixed

The function set_executor(...) can change the executor’s address but this function can be called just by the owner of the WORLD contract. The address of the new executor can be set to any arbitrary value.

However, a potential issue may arise if the executor’s address is unintentionally set to zero or if a contract lacks the implementation of the call(...) function.

Recommendation

Consider checking if the new executor’s address is not zero and if the call(...) function is available.

Resolution

First update by verifying that the new address is not zero in c804b77e9b92a058829d4171c3a5c766832d0a50. TBD for the verification of call, should be done using interfaces instead of verification of entry point existency. But the executor may be removed anyway.

6.24 Unnecessary check of address zero

FileFix commitTypeStatus
components/upgradeable.cairo—Best PracticesAcknowledged

The upgrade method is already checking that the caller is a world address. However, there is no way that caller’s address can be zero. So first assertion

assert(
self.get_contract().world().contract_address.is_non_zero(),
Errors::INVALID_WORLD_ADDRESS
);

is unnecessary in this case.

Recommendation

Consider removing this assertion.

Resolution

If the contract has the world dispatcher uninitialized in the storage, the contract address will be 0. Then, even if there is a low chance to have the get_caller_address() to be zero, this is technically possible, and the second assertion alone is not enough to prevent this situation.

6.25 Unused variables

FileFix commitTypeStatus
world.cairo
executor.cairo
9a94a39
e95153c
73d7809
c04ffa5
572fdc8
Best PracticesFixed

The codebase contains several variables that are declared but never used.

  • The function delete_entity(...) defines a model_class_hash variable that is not used;
  • The function entities(...) has an index input parameter that is never used;
  • The constant EXECUTE_ENTRYPOINT in executor.cairo is not used anywhere;

Recommendation

Consider deleting unused variables.

Resolution

This was solved by several commits: delete_entity in 9a94a397867928347955b61bd3df2bd4b3355fc3. entities() removed as never used for now in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6. EXECUTE_ENTRYPOINT removed in 73d78093f4f1e0df95b4874c8b00af80b5034601.

Update from Nethermind Security

The changes in the code introduced unused storage variable metadata_uri in the world.cairo.

Update from the client

Fixed in c04ffa5c42c31b5cf90f6fca5bd1ea7b675e938b and 572fdc8a0d46d6a286dae8014d5824e6a34acd2d.

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 Dojo team has provided documentation about their core game engine in the codebase comments and through their official documentation - Dojo Book. Moreover, the Dojo team was available to address any inquiries or concerns raised by the Nethermind auditors.

Test suite
60Tests passed0Failed

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.