I am trying to read directly from contract storage in Rust. I found the fuel-strorage and fuel-core-storage crates. However, I am having difficulty reading the bytes stored in a given storage slot. Is this something that can be done with the Rust SDK? Is it possible to read the storage slot from a script in Sway?
Hi,
You can find examples of how to use storage in Sway contracts and how to interact with them using the Rust SDK at the following links:
- Sway Contract Code: main.sw
- This contract defines storage variables and demonstrates how to read and write to them within the contract.
- When you compile this contract using
forc
(Fuel’s command-line tool), it generates astorage-storage_slots.json
file. This JSON file contains the storage keys and initial values of the contract’s storage variables. - The
storage-storage_slots.json
file is used by the Rust SDK to interact directly with the contract’s storage.
- Rust Tests: storage.rs
- This test code shows how to deploy the contract and interact with its storage from Rust.
- It demonstrates reading storage values using the generated ABI methods and the storage keys from the JSON file.
In the context of main.sw, this demonstrates how to read storage within the contract:
#[storage(read)]
fn get_sum_storage_values() -> u64 {
storage.x.read() + storage.x.read()
}
Thanks for following up!!
However, the case I am trying to solve is when the contract doesn’t expose a method to query the data in storage but you still want to be able to read it. The realistic case is that someone else deploys a contract that doesn’t have methods to query the internal contract state.
From what I’ve read it seems this isn’t currently possible. Would it be possible to make something like this with how Fuel is architected?
Also, can contracts or scripts read the storage of another contract? If so, I could use a script/contract to get the information from storage and return it as a log.
I talked to the team, but unfortunately, we don’t have the time to focus on that right now.
You can call a contract from another contract, but as you mentioned, there needs to be a method to query the data in storage.
let response = contract_caller_instance
.methods()
.read_storage_from_aother_contract(contract_with_storage_id)
.with_contracts(&[&contract_with_storage_instance])
.call()
.await?;
where contract_caller_instance has method:
fn read_storage_from_other_contract(
contract_id: ContractId,
) -> u64 {
let contract_instance = abi(LibContract, contract_id.into());
contract_instance.read_from_storage()
}
and contract_with_storage_instance has to have:
use std::storage::storage_api::read;
#[storage(read)]
fn read_from_storage() -> u64 {
storage.x.read() + storage.z.read()
}
Thanks for the quick replies and the clarification