All previous answers before used some function called get_balance
, but there is none listed like that in the api https://eosio.github.io/eosio.cdt/1.6.0/functions.html.
-
What kind of balance you are trying to get? Could you provide a little bit more context?– hanCommented Jul 16, 2019 at 7:22
Add a comment
|
1 Answer
You need to access the accounts
table of the appropriate token contract, in the scope of the token that you want to check the balance for:
struct accounts
{
eosio::asset balance;
uint64_t primary_key() const {return balance.symbol.code().raw();}
};
typedef eosio::multi_index< eosio::name("accounts"), accounts > accounts_table;
accounts_table tmp(eosio::name("TOKEN_CONTRACT"), eosio::name("ACCOUNT_NAME").value);
eosio::symbol TOKEN_SYMBOL = whatever the token symbol is;
auto itr = tmp.find(TOKEN_SYMBOL.code().raw());
eosio::check(itr != tmp.end(), "The token doesn't exist in the token contract, or the account doesn't own any of these tokens");
auto balance = itr->balance;
eosio::print("My balance is ",balance);
Where TOKEN_CONTRACT
, ACCOUNT_NAME
, and TOKEN_SYMBOL
must be known parameters
-
Thanks. I don't know how to get your example code to work.
accounts_table tmp(eosio::name("TOKEN_CONTRACT"), eosio::name("ACCOUNT_NAME"));
Can't compile, because the second argument is expected to be of type account, not name and I don't know what to insert there.– NozdrumCommented Jul 16, 2019 at 14:36 -
oops my bad, one moment. I forgot to add .value for the name scope. The code is updated now Commented Jul 16, 2019 at 14:36
-
Thanks it works now. I really don't understand why it works tho. I am not filling in this accounts_table, it gets filled by whoever TOKEN_CONTRACT is? I can just ask other contracts for the content of their tables? And does my accounts-struct have to be the same as theirs? Btw. you forgot a typedef in your multi_index-line– NozdrumCommented Jul 16, 2019 at 14:50
-
Tokens are just stored in a table. Specifically a table from the token contract. All tables are transparently visible on the blockchain. Yes the struct has to be the same as theirs, otherwise when you tried to access the table you would have serialization problems Commented Jul 17, 2019 at 8:45