Can't get all balance of contract

Here is the link to my Money Box smart contract which I am trying to get the total balance of the specified token

 fn total_balance_of(asset_id: ContractId) -> u64 {
        balance_of(contract_id(), asset_id)

But when I run this contract with following test I keep getting 0 as token balance

let contracts = [Bech32ContractId::from(contract_id)];
    let total_balance = methods
    println!("total_balance: {}", total_balance.value);

Please help)


Your link doesn’t work for me, is that a public repo?

fixed, sorry) now its public


Thanks! This looks like a type mismatch, as contract_id() returns a ContractId, so the key you provided is of type (ContractId, ContractId) instead of (Address, ContractId). You might want to consider using Identity instead, which can be either an Address or ContractId:
Blockchain Types - The Sway Programming Language

Can you please send a sample code with the problem fixed?

Tried using identity, same result.

 let identity = Identity::ContractId(contract_id);
    let total_balance = methods
    println!("total_balance: {}", total_balance.value);

And the address cannot be used as an argument because of a compilation error

  --> /Users/alexey/projects/fuel/money-box/src/main.sw:93:35
91 | 
92 |         // };
93 |         balance_of(contract_id(), asset_id)
   |                                   ^^^^^^^^ Mismatched types.
expected: ContractId
found:    Address.
help: The argument that has been provided to this function's type does not match the declared type of the parameter in the function declaration.
94 |     }
95 | }

My apologies, the type is not the issue here. It is actually just the order of the arguments passed to the balance_of function. It should be balance_of(asset_id, contract_id()) . You can see the full code for this function here: sway/context.sw at 949dfb98bd8ad0d89c5a59a33b391892e665a760 · FuelLabs/sway · GitHub


That’s works
Thanks a lot!!! :heart:

1 Like

It would be better to use this_balance(asset_id) in that case

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.