airgap-coin-lib
Version:
The airgap-coin-lib is a protocol agnostic library to prepare, sign and broadcast cryptocurrency transactions.
282 lines • 16.2 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(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 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, 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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("../../../dependencies/src/bignumber.js-9.0.0/bignumber");
var ethUtil = require("../../../dependencies/src/ethereumjs-util-5.2.0/index");
var ICoinSubProtocol_1 = require("../../ICoinSubProtocol");
var BaseEthereumProtocol_1 = require("../BaseEthereumProtocol");
var AirGapNodeClient_1 = require("../clients/node-clients/AirGapNodeClient");
var utils_1 = require("../utils/utils");
var EthereumTransaction = require('../../../dependencies/src/ethereumjs-tx-1.3.7/index');
var GenericERC20 = /** @class */ (function (_super) {
__extends(GenericERC20, _super);
function GenericERC20(options) {
var _this = _super.call(this, options) || this;
_this.options = options;
_this.isSubProtocol = true;
_this.subProtocolType = ICoinSubProtocol_1.SubProtocolType.TOKEN;
_this.contractAddress = options.config.contractAddress;
_this.symbol = options.config.symbol;
_this.name = options.config.name;
_this.marketSymbol = options.config.marketSymbol;
_this.identifier = options.config.identifier;
_this.decimals = options.config.decimals;
return _this;
}
GenericERC20.prototype.getBalanceOfPublicKey = function (publicKey) {
return __awaiter(this, void 0, void 0, function () {
var address;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
case 1:
address = _a.sent();
return [2 /*return*/, this.getBalanceOfAddresses([address])];
}
});
});
};
GenericERC20.prototype.getBalanceOfAddresses = function (addresses) {
return __awaiter(this, void 0, void 0, function () {
var balances;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(addresses.map(function (address) {
return _this.options.nodeClient.callBalanceOf(_this.contractAddress, address);
}))];
case 1:
balances = _a.sent();
return [2 /*return*/, balances.reduce(function (a, b) { return a.plus(b); }).toString(10)];
}
});
});
};
GenericERC20.prototype.signWithPrivateKey = function (privateKey, transaction) {
if (!transaction.data || transaction.data === '0x') {
transaction.data = new AirGapNodeClient_1.EthereumRPCDataTransfer(transaction.to, transaction.value).abiEncoded(); // backwards-compatible fix
}
return _super.prototype.signWithPrivateKey.call(this, privateKey, transaction);
};
GenericERC20.prototype.estimateGas = function (source, recipient, hexValue) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.options.nodeClient.estimateTransferGas(this.contractAddress, source, recipient, hexValue)];
case 1:
result = _a.sent();
return [2 /*return*/, result];
}
});
});
};
GenericERC20.prototype.estimateMaxTransactionValueFromPublicKey = function (publicKey, recipients, fee) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.getBalanceOfPublicKey(publicKey)];
});
});
};
GenericERC20.prototype.estimateFeeDefaultsFromPublicKey = function (publicKey, recipients, values, data) {
return __awaiter(this, void 0, void 0, function () {
var address, estimatedGas, gasPrise, feeStepFactor, estimatedFee, lowFee, mediumFee, highFee;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (recipients.length !== values.length) {
return [2 /*return*/, Promise.reject('recipients length does not match with values')];
}
if (recipients.length !== 1) {
return [2 /*return*/, Promise.reject('you cannot have 0 recipients')];
}
return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
case 1:
address = _a.sent();
return [4 /*yield*/, this.estimateGas(address, recipients[0], utils_1.EthereumUtils.toHex(values[0]))];
case 2:
estimatedGas = _a.sent();
return [4 /*yield*/, this.options.nodeClient.getGasPrice()];
case 3:
gasPrise = _a.sent();
feeStepFactor = new bignumber_1.default(0.5);
estimatedFee = estimatedGas.times(gasPrise);
lowFee = estimatedFee.minus(estimatedFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
mediumFee = estimatedFee;
highFee = mediumFee.plus(mediumFee.times(feeStepFactor).integerValue(bignumber_1.default.ROUND_FLOOR));
return [2 /*return*/, {
low: lowFee.shiftedBy(-this.feeDecimals).toFixed(),
medium: mediumFee.shiftedBy(-this.feeDecimals).toFixed(),
high: highFee.shiftedBy(-this.feeDecimals).toFixed()
}];
}
});
});
};
GenericERC20.prototype.prepareTransactionFromPublicKey = function (publicKey, recipients, values, fee) {
return __awaiter(this, void 0, void 0, function () {
var wrappedValues, wrappedFee, balance, _a, address, ethBalance, _b, estimatedGas, txCount, gasPrice, transaction;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
wrappedValues = values.map(function (value) { return new bignumber_1.default(value); });
wrappedFee = new bignumber_1.default(fee);
if (recipients.length !== wrappedValues.length) {
throw new Error('recipients length does not match with values');
}
if (recipients.length !== 1) {
throw new Error('you cannot have 0 recipients');
}
_a = bignumber_1.default.bind;
return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
case 1:
balance = new (_a.apply(bignumber_1.default, [void 0, _c.sent()]))();
if (!balance.isGreaterThanOrEqualTo(wrappedValues[0])) return [3 /*break*/, 8];
return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
case 2:
address = _c.sent();
_b = bignumber_1.default.bind;
return [4 /*yield*/, _super.prototype.getBalanceOfAddresses.call(this, [address])];
case 3:
ethBalance = new (_b.apply(bignumber_1.default, [void 0, _c.sent()]))();
return [4 /*yield*/, this.estimateGas(address, recipients[0], utils_1.EthereumUtils.toHex(wrappedValues[0].toFixed()))];
case 4:
estimatedGas = _c.sent();
if (!ethBalance.isGreaterThanOrEqualTo(wrappedFee)) return [3 /*break*/, 6];
return [4 /*yield*/, this.options.nodeClient.fetchTransactionCount(address)];
case 5:
txCount = _c.sent();
gasPrice = wrappedFee.isEqualTo(0)
? new bignumber_1.default(0)
: wrappedFee.div(estimatedGas).integerValue(bignumber_1.default.ROUND_CEIL);
transaction = {
nonce: utils_1.EthereumUtils.toHex(txCount),
gasLimit: utils_1.EthereumUtils.toHex(estimatedGas.toFixed()),
gasPrice: utils_1.EthereumUtils.toHex(gasPrice.toFixed()),
to: this.contractAddress,
value: utils_1.EthereumUtils.toHex(new bignumber_1.default(0).toFixed()),
chainId: this.options.network.extras.chainID,
data: new AirGapNodeClient_1.EthereumRPCDataTransfer(recipients[0], utils_1.EthereumUtils.toHex(wrappedValues[0].toFixed())).abiEncoded()
};
return [2 /*return*/, transaction];
case 6: throw new Error('not enough ETH balance');
case 7: return [3 /*break*/, 9];
case 8: throw new Error('not enough token balance');
case 9: return [2 /*return*/];
}
});
});
};
GenericERC20.prototype.getTransactionsFromAddresses = function (addresses, limit, cursor) {
var _this = this;
return new Promise(function (overallResolve, overallReject) {
var promises = [];
for (var _i = 0, addresses_1 = addresses; _i < addresses_1.length; _i++) {
var address = addresses_1[_i];
promises.push(_this.options.infoClient.fetchContractTransactions(_this, _this.contractAddress, address, limit, cursor));
}
Promise.all(promises)
.then(function (values) {
var page = Math.max.apply(Math, values.map(function (txResult) { return txResult.cursor.page; }));
overallResolve(values.reduce(function (a, b) {
return { transactions: a.transactions.concat(b.transactions), cursor: { page: page } };
}));
})
.catch(overallReject);
});
};
GenericERC20.prototype.getTransactionDetailsFromSigned = function (signedTx) {
return __awaiter(this, void 0, void 0, function () {
var ethTxs, ethTx, extractedTx, tokenTransferDetails;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.getTransactionDetailsFromSigned.call(this, signedTx)];
case 1:
ethTxs = _a.sent();
if (ethTxs.length !== 1) {
throw new Error('More than one ETH transaction detected.');
}
ethTx = ethTxs[0];
extractedTx = new EthereumTransaction(signedTx.transaction);
tokenTransferDetails = new AirGapNodeClient_1.EthereumRPCDataTransfer("0x" + extractedTx.data.toString('hex'));
ethTx.to = [ethUtil.toChecksumAddress(tokenTransferDetails.recipient)];
ethTx.amount = new bignumber_1.default(tokenTransferDetails.amount).toString(10);
return [2 /*return*/, [ethTx]];
}
});
});
};
GenericERC20.prototype.getTransactionDetails = function (unsignedTx) {
return __awaiter(this, void 0, void 0, function () {
var unsignedEthereumTx, ethTxs, ethTx, tokenTransferDetails;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
unsignedEthereumTx = unsignedTx;
return [4 /*yield*/, _super.prototype.getTransactionDetails.call(this, unsignedEthereumTx)];
case 1:
ethTxs = _a.sent();
if (ethTxs.length !== 1) {
throw new Error('More than one ETH transaction detected.');
}
ethTx = ethTxs[0];
tokenTransferDetails = new AirGapNodeClient_1.EthereumRPCDataTransfer(unsignedEthereumTx.transaction.data);
ethTx.to = [ethUtil.toChecksumAddress(tokenTransferDetails.recipient)];
ethTx.amount = new bignumber_1.default(tokenTransferDetails.amount).toString(10);
return [2 /*return*/, [ethTx]];
}
});
});
};
return GenericERC20;
}(BaseEthereumProtocol_1.BaseEthereumProtocol));
exports.GenericERC20 = GenericERC20;
//# sourceMappingURL=GenericERC20.js.map