Как получить остаток на счете в ThunderCore? - PullRequest
0 голосов
/ 17 апреля 2020

Я хочу программно запросить баланс адреса или списка адресов. Какой лучший способ сделать это?

1 Ответ

0 голосов
/ 20 апреля 2020

Чтобы получить баланс 0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1 в последнем блоке, выполните:

curl -X POST -H 'Content-Type: application/json' -s --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xad23b02673214973e354d41e19999d9e01f3be58", "latest"], "id":1}' https://mainnet-rpc.thundercore.com/

Вывод: {"jsonrpc":"2.0","id":1,"result":"0xde0b6b3a7640000"}

Получение баланса одного счета с помощью web3 . js:

const Eth = require('web3-eth');
const Web3 = require('web3');
const web3Provider = () => {
  return Eth.giveProvider || 'https://mainnet-rpc.thundercore.com';
}
const balance = async (address) => {
  const eth = new Eth(web3Provider());
  return Web3.utils.fromWei(await eth.getBalance(address));
}

Пример сеанса

const address = '0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1';
await balance(address) // -> '1'

Единицы

  • 0xde0b6b3a7640000 равно 10**18
  • Используя Ethereum терминологию, fromWei преобразует 10^18 Wei в 1 Ether, или используя терминологию Thunder
  • Используя терминологию ThunderCore, fromWei преобразует 10^18 Элла в 1 ТТ
  • fromWei(0xde0b6b3a7640000) равно fromWei(10**18) равно 1

Пакетный запрос для запроса баланса

  • Для массива адресов вы можете использовать JSON -RP C 2.0's Пакетные запросы для сохранения сетевых циклов
  • При запросе https://mainnet-rpc.thundercore.com ограничьте размер пакета до вокруг 30

Следующий класс оборачивает web3.js-1.2.6 s BatchRequest и возвращает ему Javascript Promise:

class BatchRequest {
  constructor(web3) {
    this.b = new web3.BatchRequest();
    this.results = [];
    this.resolve = null;
    this.reject = null;
    this.resultsFilled = 0;
  }
  web3BatchRequestCallBack(index, err, result) {
    /* if any request in our batch fails, reject the promise we return from `execute` */
    if (err) {
      this.reject(new Error(`request ${index} failed: ${err}`))
      return;
    }
    this.results[index] = result;
    this.resultsFilled++;
    if (this.resultsFilled === this.results.length) {
      this.resolve(this.results);
    }
  }
  resultPromiseExecutor(resolve, reject) {
    this.resolve = resolve;
    this.reject = reject;
  }
  add(method /* web3-core-method.Method */) {
    const index = this.results.length;
    method.callback = (err, result) => {
      this.web3BatchRequestCallBack(index, err, result)
    };
    this.b.add(method);
    this.results.push(undefined);
  }
  execute() /*: Promise */ {
    const p = new Promise((resolve, reject) => { this.resultPromiseExecutor(resolve, reject) });
    /* must arrange for resultPromiseExecutor to be called before b.execute */
    this.b.execute();
    return p;
  }
}
const balanceBatch = async (addresses) => {
  const eth = new Eth(web3Provider());
  const b = new BatchRequest(eth);
  for (a of addresses) {
    b.add(eth.getBalance.request(a));
  }
  const ellaS = await b.execute();
  const ttS = [];
  for (e of ellaS) {
    ttS.push(Web3.utils.fromWei(e));
  }
  return ttS;
}

batch-balance-test.js

const Web3 = require('web3');
(async() => {
  const web3 = new Web3('https://mainnet-rpc.thundercore.com');
  const results = await balanceBatch([
    '0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1',
    '0x4f3c8e20942461e2c3bdd8311ac57b0c222f2b82',
  ]);
  console.log('results:', results);
})();

Пример сеанса

$ node batch-balance-test.js
results: [ '1', '84.309961496' ]

См Завершите настройку проекта здесь в ветке balance репо field-support.

...