UNPKG

tokenlon-sdk

Version:

imToken Tokenlon API for node

173 lines 8.23 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var _this = this; Object.defineProperty(exports, "__esModule", { value: true }); var ethAbi = require("ethereumjs-abi"); var ethUtil = require("ethereumjs-util"); var Tx = require("ethereumjs-tx"); var _ = require("lodash"); var web3_wrapper_1 = require("../lib/web3-wrapper"); var abi_1 = require("./abi"); var math_1 = require("./math"); // Executes a message call or transaction, which is directly executed in the VM of the node, // but never mined into the blockchain and returns the amount of the gas used. exports.getEstimateGas = function (tx) { return new Promise(function (resolve, reject) { // console.log(`[web3 req] estimateGas params: ${JSON.stringify(tx)}`) web3_wrapper_1.default.eth.estimateGas(tx, function (err, gas) { if (!err) { resolve(gas); } else { reject(err); } }); }); }; // Get the numbers of transactions sent from this address. exports.getNonce = function (address) { return new Promise(function (resolve, reject) { // console.log(`[web3 req] getTransactionCount params: ${address}`) web3_wrapper_1.default.eth.getTransactionCount(address, function (err, nonce) { if (!err) { // console.log(`[web3 res] getTransactionCount: ${nonce}`) resolve(nonce); } else { reject(err); } }); }); }; var formatArgs = function (args) { return args.map(function (item) { if (_.isArray(item)) return formatArgs(item); if (math_1.isBigNumber(item)) return item.toString(); return item; }); }; /** * @params.contractName * @params.method contract method name * @params.args contract method arguments * @description * generate data 的 三种实现方式 * 1. 两年前的 https://github.com/ethereum/solidity.js (未实验) * 2. web3.js lib/solidity/coder (拆不出来) * https://github.com/ethereum/web3.js/blob/6d3e61a010501011a107a79574cc7516900fa9e4/lib/solidity/coder.js * https://github.com/ethereum/web3.js/blob/db6efd5f2309f9aeab6283383b3f4a3d1dcb7177/lib/web3/function.js#L92 * https://github.com/ethereum/web3.js/blob/db6efd5f2309f9aeab6283383b3f4a3d1dcb7177/lib/web3.js#L107 * 3. ethereumjs-abi https://github.com/ethereumjs/ethereumjs-abi/blob/master/lib/index.js */ exports.encodeData = function (contractName, method, args) { var types = abi_1.getAbiInputTypes(contractName, method); var signatureBuffer = ethAbi.methodID(method, types); var mainBuffer = ethAbi.rawEncode(types, formatArgs(args)); var data = ethUtil.bufferToHex(Buffer.concat([signatureBuffer, mainBuffer])); return data; }; exports.getTokenBalance = function (_a) { var address = _a.address, contractAddress = _a.contractAddress; return new Promise(function (resolve, reject) { web3_wrapper_1.default.eth.call({ to: contractAddress, data: exports.encodeData('token', 'balanceOf', [address]), }, function (err, res) { if (err) { return reject(err); } resolve(math_1.toBN(res)); }); }); }; // use ethereumjs-tx and web3.eth.sendRawTransaction to send transaction by privateKey // value must be a decimal processed number exports.sendTransaction = function (params) { return __awaiter(_this, void 0, void 0, function () { var address, privateKey, gasPrice, to, value, gasLimit, data, nonce, estimateGas, _e_1, privateKeyBuffer, gas, rawTx, tx, serializedTx; return __generator(this, function (_a) { switch (_a.label) { case 0: address = params.address, privateKey = params.privateKey, gasPrice = params.gasPrice, to = params.to, value = params.value, gasLimit = params.gasLimit, data = params.data; return [4 /*yield*/, exports.getNonce(address)]; case 1: nonce = _a.sent(); estimateGas = 0; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, exports.getEstimateGas({ from: address, to: to, value: web3_wrapper_1.default.toHex(value), data: data, })]; case 3: estimateGas = _a.sent(); return [3 /*break*/, 5]; case 4: _e_1 = _a.sent(); return [3 /*break*/, 5]; case 5: privateKeyBuffer = new Buffer(privateKey, 'hex'); gas = estimateGas && gasLimit ? Math.max(estimateGas, gasLimit) : (estimateGas || gasLimit); rawTx = { to: to, data: data || '', nonce: web3_wrapper_1.default.toHex(nonce), gasPrice: web3_wrapper_1.default.toHex(gasPrice), gasLimit: web3_wrapper_1.default.toHex(gas), value: web3_wrapper_1.default.toHex(value), }; tx = new (Tx.default ? Tx.default : Tx)(rawTx); tx.sign(privateKeyBuffer); serializedTx = tx.serialize(); return [2 /*return*/, new Promise(function (resolve, reject) { web3_wrapper_1.default.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function (err, txHash) { if (!err) { resolve(txHash); } else { reject(err); } }); })]; } }); }); }; //# sourceMappingURL=ethereum.js.map