eos-utils
Version:
Powerful util library based on eosjs.
199 lines (198 loc) • 6.01 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
// import BigNumber from 'bignumber.js';
const assert_1 = require('assert');
const eos_token_info_1 = require('eos-token-info');
const eosjs_1 = require('eosjs');
const eosjs_ecc_1 = require('eosjs-ecc');
const eosjs_jssig_1 = require('eosjs/dist/eosjs-jssig'); // development only
const fetch = require('node-fetch'); // node only; not needed in browsers
const { TextEncoder, TextDecoder } = require('util');
exports.EOS_API_ENDPOINTS = [
'http://api.main.alohaeos.com',
'http://eos.greymass.com',
'http://eos.infstones.io',
'http://eos.unlimitedeos.com:7777',
'http://peer1.eoshuobipool.com:8181',
'http://peer2.eoshuobipool.com:8181',
'https://eos.greymass.com',
];
exports.EOS_API_ENDPOINTS_BLACK_LIST = [
'http://api.eossweden.org',
'http://bp.whaleex.com',
'https://bp.whaleex.com',
'https://eos.eoscafeblock.com',
'https://node1.zbeos.com',
];
exports.EOS_QUANTITY_PRECISION = 4;
function getRandomRpc(apiEndpoint) {
const url =
apiEndpoint ||
exports.EOS_API_ENDPOINTS[Math.floor(Math.random() * exports.EOS_API_ENDPOINTS.length)];
return new eosjs_1.JsonRpc(url, { fetch });
}
exports.getRandomRpc = getRandomRpc;
function getRandomApi(privateKey, apiEndpoint) {
const rpc = getRandomRpc(apiEndpoint);
const api = new eosjs_1.Api({
rpc,
signatureProvider: new eosjs_jssig_1.JsSignatureProvider([privateKey]),
textDecoder: new TextDecoder(),
textEncoder: new TextEncoder(),
});
return api;
}
exports.getRandomApi = getRandomApi;
async function sendTransaction(actions, privateKey, apiEndpoint) {
return getRandomApi(privateKey, apiEndpoint).transact(
{
actions,
},
{
blocksBehind: 3,
expireSeconds: 300,
},
);
}
exports.sendTransaction = sendTransaction;
function calcDecimals(quantity) {
if (!quantity.includes('.')) return 0;
return quantity.split(' ')[0].split('.')[1].length;
}
/**
* Create a transfer action.
*
* @param from The sender's EOS account
* @param to The receiver's EOS account
* @param symbol The currency symbol, e.g., EOS, USDT, EIDOS, DICE, KEY, etc.
* @param quantity The quantity to send
* @param memo memo
*/
function createTransferAction(from, to, symbol, quantity, memo = '') {
const tokenInfo = eos_token_info_1.getTokenInfo(symbol);
assert_1.strict.equal(
calcDecimals(quantity),
tokenInfo.decimals,
`The decimals of quantity is NOT equal to ${tokenInfo.decimals}`,
);
const action = {
account: tokenInfo.contract,
name: 'transfer',
authorization: [
{
actor: from,
permission: 'active',
},
],
data: {
from,
to,
quantity: `${quantity} ${symbol}`,
memo,
},
};
return action;
}
exports.createTransferAction = createTransferAction;
/**
* Transfer EOS or EOS token to another account.
*
* @param from The sender's EOS account
* @param privateKey The sender's EOS private key
* @param to The receiver's EOS account
* @param symbol The currency symbol, e.g., EOS, USDT, EIDOS, DICE, KEY, etc.
* @param quantity The quantity to send
* @param memo memo
*/
async function transfer(from, privateKey, to, symbol, quantity, memo = '') {
const action = createTransferAction(from, to, symbol, quantity, memo);
return sendTransaction([action], privateKey);
}
exports.transfer = transfer;
function numericFromName(accountName) {
const sb = new eosjs_1.Serialize.SerialBuffer({
textEncoder: new TextEncoder(),
textDecoder: new TextDecoder(),
});
sb.pushName(accountName);
return eosjs_1.Numeric.binaryToDecimal(sb.getUint8Array(8));
}
exports.numericFromName = numericFromName;
async function queryTransaction(txid, blockNum, apiEndpoint) {
const rpc = getRandomRpc(apiEndpoint);
const response = await rpc.history_get_transaction(txid, blockNum);
if (response.transaction_id || response.id) {
return response;
}
throw Error('Unknown response format');
}
exports.queryTransaction = queryTransaction;
async function getCurrencyBalance(account, symbol, apiEndpoint) {
const balanceInfo = await getRandomRpc(apiEndpoint).get_currency_balance(
eos_token_info_1.getTokenInfo(symbol).contract,
account,
symbol,
);
if (balanceInfo.length === 0) {
return 0;
}
const balance = parseFloat(balanceInfo[0].split(' ')[0]);
return balance;
}
exports.getCurrencyBalance = getCurrencyBalance;
/**
* Check the existance of an account.
*
* @param accountName EOS account name
* @return true if exists, otherwise false
*/
async function accountExists(accountName, apiEndpoint) {
const rpc = getRandomRpc(apiEndpoint);
const { rows } = await rpc.get_table_rows({
json: true,
code: 'eosio',
scope: accountName,
table: 'userres',
lower_bound: accountName,
upper_bound: accountName,
});
return rows.length > 0;
}
exports.accountExists = accountExists;
/**
* Get the account names of a public key.
*
* @param publicKey EOS public key
* @returns an array of account names, empty if not exist
*/
async function getKeyAccounts(publicKey, apiEndpoint) {
if (!eosjs_ecc_1.isValidPublic(publicKey)) {
throw new Error(`Invalid public key: ${publicKey}`);
}
const rpc = getRandomRpc(apiEndpoint);
const response = await rpc.history_get_key_accounts(publicKey);
return response.account_names;
}
exports.getKeyAccounts = getKeyAccounts;
async function getTableRows(
{ code, scope, table, lower_bound = '', upper_bound = '', limit = 100 },
apiEndpoint,
) {
const rpc = getRandomRpc(apiEndpoint);
return rpc.get_table_rows({
json: true,
code,
scope,
table,
lower_bound,
upper_bound,
limit,
});
}
exports.getTableRows = getTableRows;
async function getCurrencyStats(contract, symbol, apiEndpoint) {
const rpc = getRandomRpc(apiEndpoint);
const stats = await rpc.get_currency_stats(contract, symbol);
return stats[symbol];
}
exports.getCurrencyStats = getCurrencyStats;