TransWikia.com

How to read tables from other smart contracts?

EOS.IO Asked by Leo Ribeiro on August 20, 2021

I tried to look for inside the EOS repository and contracts examples but I could not find anything like this. I want to know how can I read another contract table.

So, as an example: my contract needs to check the balance of EOS tokens of an specific account. How can I do that reading from eosio.token contract?

One Answer

When declaring a multi_index to use as a table a contract (eg. contracta) you would typically create a struct and typedef similar to this:

// @abi table myobjects
struct myobject {
    name sender;
    // ... other properties here

   EOSLIB_SERIALIZE(myobject, (sender)(...))
}

typedef multi_index<N(myobjects), myobject> myobjects_t;

and then create an instance to use within the contracta code:

auto db = myobjects_t(_self, _self);

The first _self refers to the code that defined the table and the second refers to the scope for the table in this case both are referring to contracta.

In order for contractb to have access to that data it would need to also define the struct and typedef as above but when creating an instance for access the _self would be replaced by N(contracta) and if the scope for the table is also _self that should also be the same.

The struct would need to have the same property names, types and order of definition and also be serialised in the same order. The ABI name and index type would also need to match. Then the data would be accessible for reading as if it's in the same contract. If both contracts are part of your own code the common structs and typedefs could be declared and shared in a common header (.hpp). Otherwise the structs could be reverse engineered into C++ from reading the ABI code from the blockchain using get_code.

Correct answer by Dallas Johnson on August 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP