Question: `get_table_rows` from Checksum256 as secondary index
DenisCarriere opened this issue · comments
Question
What is the best way to query a table row with Checksum256 as secondary index?
JS Code example
https://codesandbox.io/p/sandbox/snowy-sunset-lrqqmm?file=%2Findex.js
Smart Contract (EOS EVM)
struct [[eosio::table]] [[eosio::contract("evm_contract")]] account {
uint64_t id;
bytes eth_address;
uint64_t nonce;
bytes balance;
std::optional<uint64_t> code_id;
uint64_t primary_key()const { return id; }
checksum256 by_eth_address()const {
return make_key(eth_address);
}
uint256be get_balance()const {
uint256be res;
std::copy(balance.begin(), balance.end(), res.bytes);
return res;
}
EOSLIB_SERIALIZE(account, (id)(eth_address)(nonce)(balance)(code_id));
};
Works with eosc
$ eosc -u https://jungle4.api.eosnation.io get table eosio.evm eosio.evm account --lower-bound aa2F34E41B397aD905e2f48059338522D05CA534 --upper-bound aa2F34E41B397aD905e2f48059338522D05CA534 --key-type sha256 --index 2
{
"more": false,
"rows": [
{
"id": 6241,
"eth_address": "aa2f34e41b397ad905e2f48059338522d05ca534",
"nonce": 10,
"balance": "0000000000000000000000000000000000000000000000053221ae6683fe8801",
"code_id": null
}
]
}
It looks like it'll take in the string you initially provided, and then as long as you specify the key_type
value it'll handle everything properly. I think behind the scenes its actually converting everything back to a string anyways, since that's ultimately what the API endpoint is expecting for the query.
Functional:
https://codesandbox.io/p/sandbox/snowy-sunset-lrqqmm?file=%2Findex.js
Code in the event the sandbox goes away:
import { APIClient } from "@wharfkit/session";
import fetch from "node-fetch";
export const rpc = new APIClient({
url: "https://jungle4.api.eosnation.io",
fetch,
});
export function get_balance(address) {
address = address.replace("0x", "");
return rpc.v1.chain.get_table_rows({
code: "eosio.evm",
scope: "eosio.evm",
table: "account",
index_position: "secondary",
lower_bound: address,
upper_bound: address,
key_type: "sha256",
json: true,
limit: 1,
});
}
const address = "0xaa2F34E41B397aD905e2f48059338522D05CA534";
get_balance(address).then((response) => console.log(response));
For future reference, this is the Typescript code to get EVM balance using Wharfkit
export async function get_balance(address: any) {
address = address.replace("0x", "");
const response = await rpc.v1.chain.get_table_rows({
code: "eosio.evm",
scope: "eosio.evm",
table: "account",
index_position: "secondary",
lower_bound: address,
upper_bound: address,
json: true,
limit: 1,
key_type: "sha256",
})
if (response.rows.length === 0) return 0.0
return parseInt(response.rows[0].balance, 16) / 10 ** 18;
}