How can I pass an account name as the lower and upper bound in the getTableRows method?
I've looked at types.hpp and saw the string_to_name method, is there a similar method in EOSjs?
EOS.IO Stack Exchange is a question and answer site for users and developers of distributed applications built on top of the blockchain operating system, EOS.IO. It only takes a minute to sign up.
Sign up to join this communityHow can I pass an account name as the lower and upper bound in the getTableRows method?
I've looked at types.hpp and saw the string_to_name method, is there a similar method in EOSjs?
The eosjs library has a format module that will transform account name strings into the appropriate table keys...
const Eos = require("eosjs")
const BigNumber = require("bignumber.js")
const accountName = 'myaccount'
const encodedName = new
BigNumber(Eos.modules.format.encodeName(accountName, false))
** Notes:
false
to format.encodeName
, otherwise, you'll be transforming account names using littleEndian=true
Then, you can call getTableRows
like so...
Eos.Localnet({}).getTableRows({
code: contractName.toString(),
json: json,
limit: limit,
lower_bound: encodedName.toString(),
scope: contractName.toString(),
table: tableName.toString(),
upper_bound: encodedName.plus(1).toString()
})
Eos.modules.format.encodeName
in eosjs 20.
Aug 14, 2019 at 14:06
Here is an example using eosjs@20
const BigNumber = require('bignumber.js')
const { Serialize, Numeric } = require('eosjs')
const { TextEncoder, TextDecoder } = require('util')
const numericFromName = (accountName) => {
const sb = new Serialize.SerialBuffer({
textEncoder: new TextEncoder(),
textDecoder: new TextDecoder()
})
sb.pushName(accountName)
return Numeric.binaryToDecimal(sb.getUint8Array(8));
}
const checkUserExists = async ({ blockchain, accountName }) => {
const numericAccountName = numericFromName(accountName)
const { rows } = await blockchain.rpc.get_table_rows({
code: 'accounts',
scope: 'accounts',
table: 'users',
json: true,
lower_bound: numericAccountName,
upper_bound: BigNumber(numericAccountName).plus(1)
})
return rows.length > 0
}
module.exports = checkUserExists