1

In my contract, I'd like to be able to check how much EOS an account has. For that, I'd write some C++ code like this:

token::accounts the_table("eosio.token"_n, "useraccount1"_n.value);
auto it = the_table.begin();
auto how_much = it -> balance;

Here, I'd use the type token::accounts from the eosio.token contract.

The problem is that, in the official eosio.token contract, this type is private, so my code above does not compile. So, instead of just an #include ".../eosio.token.hpp", now I copy the type declaration to the code of my contract, like this:

struct [[eosio::table]] account {
    asset balance;
    uint64_t primary_key() const {return balance.symbol.code().raw();}
};

typedef eosio::multi_index <"accounts"_n, account> accounts;

Copying and modifying the data structures, just to be able to access them, is bad coding practice. But maybe I'm using a wrong approach here. So my question here is two-fold:

  1. Why are the types in the official code private?
  2. How to better see from within a contract how much EOS an account has?
3
  • Possible duplicate of get token balance from another contract
    – Ami Heines
    Nov 11, 2018 at 16:56
  • 1
    @AmiHeines Thanks for the link! It's related, and one of the answer contains the premise of my question. Still, my question is about a particular shortcoming of that answer, which is not and should not be addressed there.
    – Gassa
    Nov 11, 2018 at 20:53
  • Perhaps the eosio.token contract needs to be changed and the struct should be moved to the public section of the class. Try raising an issue in the github repo.
    – Ami Heines
    Nov 11, 2018 at 22:09

1 Answer 1

4

The contract rightfully encapsulates the implementation details as private.

Instead, it provides the following function as the public interface:

static asset get_balance( name token_contract_account, name owner, symbol_code sym_code )

A better version of the code to get EOS balance is thus as follows:

auto how_much = token::get_balance("eosio.token"_n, "useraccount1"_n, symbol_code("EOS"));

The problem was that I didn't notice the function on my first read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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