crypto-client
Version:
An unified client for all cryptocurrency exchanges.
133 lines (132 loc) • 4.78 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrencyBalance = exports.transfer = exports.createTransferAction = exports.sendTransaction = void 0;
const client_1 = require("@dfuse/client");
const assert_1 = require("assert");
const eos_token_info_1 = require("eos-token-info");
const eosjs_1 = require("eosjs");
const eosjs_jssig_1 = require("eosjs/dist/eosjs-jssig");
const node_fetch_1 = __importDefault(require("node-fetch"));
const text_encoding_1 = require("text-encoding");
const config_1 = require("../config");
Object.assign(global, { fetch: require('node-fetch') }); // eslint-disable-line global-require
// Object.assign(global, { WebSocket: require('ws') });
Object.assign(global, { WebSocket: {} });
function createCustomizedFetch(client) {
const customizedFetch = async (input, init) => {
if (init.headers === undefined) {
init.headers = {}; // eslint-disable-line no-param-reassign
}
// This is highly optimized and cached, so while the token is fresh, this is very fast
const apiTokenInfo = await client.getTokenInfo();
const headers = init.headers;
headers.Authorization = `Bearer ${apiTokenInfo.token}`;
headers['X-Eos-Push-Guarantee'] = 'in-block';
return node_fetch_1.default(input, init);
};
return customizedFetch;
}
async function sendTransaction(actions, privateKey) {
const client = client_1.createDfuseClient({
apiKey: config_1.USER_CONFIG.DFUSE_API_KEY,
network: 'mainnet',
});
const rpc = new eosjs_1.JsonRpc(client.endpoints.restUrl, {
fetch: createCustomizedFetch(client),
});
const api = new eosjs_1.Api({
rpc,
signatureProvider: new eosjs_jssig_1.JsSignatureProvider([privateKey]),
textDecoder: new text_encoding_1.TextDecoder(),
textEncoder: new text_encoding_1.TextEncoder(),
});
try {
const result = await api
.transact({
actions,
}, {
blocksBehind: 360,
expireSeconds: 3600,
})
.catch((e) => {
return e;
});
client.release();
return result;
}
catch (e) {
return e;
}
}
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;
async function getCurrencyBalance(account, symbol) {
assert_1.strict.ok(config_1.USER_CONFIG.DFUSE_API_KEY);
const tokenInfo = eos_token_info_1.getTokenInfo(symbol);
if (tokenInfo === undefined) {
return -1;
// return new Error(`Can NOT find token ${symbol} on EOS chain`);
}
const client = client_1.createDfuseClient({
apiKey: config_1.USER_CONFIG.DFUSE_API_KEY,
network: 'mainnet',
});
const resp = await client.stateTable(tokenInfo.contract, account, 'accounts');
const { balance } = resp.rows[0].json;
client.release();
return parseFloat(balance.split(' ')[0]);
}
exports.getCurrencyBalance = getCurrencyBalance;