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

https://github.com/sway-gang/money-box/blob/total_balance_of/src/main.sw

 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

https://github.com/sway-gang/money-box/blob/total_balance_of/tests/local_tests/main_test.rs

let contracts = [Bech32ContractId::from(contract_id)];
    let total_balance = methods
        .total_balance_of(contract_id)
        .set_contracts(&contracts)
        .simulate()
        .await
        .unwrap();
    println!("total_balance: {}", total_balance.value);

Please help)

4 Likes

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

fixed, sorry) now its public

2 Likes

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
        .total_balance_of(identity)
        .set_contracts(&cotarcts)
        .simulate()
        .await
        .unwrap();
    println!("total_balance: {}", total_balance.value);

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

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

3 Likes

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

2 Likes

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

2 Likes

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