3

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?

  • Maybe you should clearify what you are trying to achieve so others get it better and the question is more useful when searched. – TeeAttack42 Jun 13 '18 at 19:44
6

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:

  • Be sure to pass false to format.encodeName, otherwise, you'll be transforming account names using littleEndian=true
  • You'll want to use the BigNumber JS library, otherwise, any arithmetic is likely to be incorrect.

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()
})
  • Unfortunately, there's no Eos.modules.format.encodeName in eosjs 20. – Andrei Arsenin Aug 14 at 14:06
1

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

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.