4

I want to get my contract currency balance within my contract code, but the eosio::account::get (account_balance &acnt) cann't use, so how can I do that?

3

If you are using eosio.token to create tokens, you can easily get your balance from the eosio.token table, you don't need to define a new table structure it's already in eosio.token . All you have to do is to add a new action to your contract just like this :

#include <eosiolib/eosio.token.hpp>   // right path to eosio.token.hpp file
void getBalance(account_name owner){
    eosio::token t(N(eosio.token));
    const auto sym_name = eosio::symbol_type(S(4,EOS)).name();
    const auto my_balance = t.get_balance(N(owner), sym_name );
    eosio::print("My balance is ", my_balance); 
}

before that you need to import eosio.token.hpp into your contract.

1

Check this answer: https://eosio.stackexchange.com/a/70/54

It should fit for you, use the table accounts with the account_name scope, code is eosio.token.

  • If I need to define account struct and typedef accounts in my contract? I do that but it seems didn't work for me. My eos version is 4.1, here is my code accounts accountstable(N(eosio.token), _self); const auto &ac = accountstable.get(CORE_SYMBOL); return ac.balance; – yang24201 May 24 '18 at 1:29
0

Adding to Nirdesh's answer: if you are using eosio.cdt >= 1.3.0 you'll have to adapt the code as 1.3.0 introduces a lot of breaking changes (i.e removing symbol_type). Check the release notes here: https://github.com/EOSIO/eosio.cdt/releases/tag/v1.3.0; symbol.hpp and asset.hpp suffer a lot of changes that are relevant to this answer.

eosio.contracts, where eosio.token contract with eosio.token.hpp is located, also suffered breaking changes lately (not sure if at the same time as the eosio.cdt 1.3.0 changes). For the token class for example, on my version which is 1.4.0, the constructor is no longer there and the methods that a token instance was needed for are all replaced with static methods.

Therefore, after including token.hpp the code becomes:

asset get_balance(name account, symbol_code code)
{
    asset account_balance = token::get_balance("eosio.token"_n, account, code);
    return account_balance;
}

where get_balance is now a static method that belongs to the token class and symbol_code is a new class introduced in symbol.hpp with eosio.cdt 1.3.0.

My advice is to look at the source code of your libraries and adapt SO answers accordingly if you're taking inspiration from older SO answers and things don't work; I learned this the hard way :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.