airgap-coin-lib
Version:
The airgap-coin-lib is a protocol agnostic library to prepare, sign and broadcast cryptocurrency transactions.
529 lines • 28.9 kB
JavaScript
"use strict";
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 index_1 = require("../../dependencies/src/bip39-2.5.0/index");
var bitcoinJS = require("../../dependencies/src/bitgo-utxo-lib-5d91049fd7a988382df81c8260e244ee56d57aac/src/index");
var ethUtil = require("../../dependencies/src/ethereumjs-util-5.2.0/index");
var ProtocolSymbols_1 = require("../../utils/ProtocolSymbols");
var subProtocols_1 = require("../../utils/subProtocols");
var ICoinSubProtocol_1 = require("../ICoinSubProtocol");
var EthereumCryptoClient_1 = require("./EthereumCryptoClient");
var EthereumProtocolOptions_1 = require("./EthereumProtocolOptions");
var utils_1 = require("./utils/utils");
var EthereumTransaction = require('../../dependencies/src/ethereumjs-tx-1.3.7/index');
var BaseEthereumProtocol = /** @class */ (function () {
function BaseEthereumProtocol(options) {
if (options === void 0) { options = new EthereumProtocolOptions_1.EthereumProtocolOptions(); }
this.options = options;
this.symbol = 'ETH';
this.name = 'Ethereum';
this.marketSymbol = 'eth';
this.feeSymbol = 'eth';
this.feeDefaults = {
low: '0.00021',
medium: '0.000315',
high: '0.00084' // 21000 Gas * 40 Gwei
};
this.decimals = 18;
this.feeDecimals = 18;
this.identifier = ProtocolSymbols_1.MainProtocolSymbols.ETH;
this.units = [
{
unitSymbol: 'ETH',
factor: '1'
},
{
unitSymbol: 'GWEI',
factor: '0.000000001'
},
{
unitSymbol: 'WEI',
factor: '0.000000000000000001'
}
];
this.supportsHD = false;
this.standardDerivationPath = "m/44'/60'/0'/0/0";
this.addressIsCaseSensitive = false;
this.addressValidationPattern = '^0x[a-fA-F0-9]{40}$';
this.addressPlaceholder = '0xabc...';
this.network = bitcoinJS.networks.bitcoin;
}
Object.defineProperty(BaseEthereumProtocol.prototype, "subProtocols", {
get: function () {
return subProtocols_1.getSubProtocolsByIdentifier(this.identifier, this.options.network);
},
enumerable: true,
configurable: true
});
BaseEthereumProtocol.prototype.getBlockExplorerLinkForAddress = function (address) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.options.network.blockExplorer.getAddressLink(address)];
});
});
};
BaseEthereumProtocol.prototype.getBlockExplorerLinkForTxId = function (txId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.options.network.blockExplorer.getTransactionLink(txId)];
});
});
};
BaseEthereumProtocol.prototype.getPublicKeyFromMnemonic = function (mnemonic, derivationPath, password) {
return __awaiter(this, void 0, void 0, function () {
var secret;
return __generator(this, function (_a) {
secret = index_1.mnemonicToSeed(mnemonic, password);
return [2 /*return*/, this.getPublicKeyFromHexSecret(secret, derivationPath)];
});
});
};
BaseEthereumProtocol.prototype.getPrivateKeyFromMnemonic = function (mnemonic, derivationPath, password) {
return __awaiter(this, void 0, void 0, function () {
var secret;
return __generator(this, function (_a) {
secret = index_1.mnemonicToSeed(mnemonic, password);
return [2 /*return*/, this.getPrivateKeyFromHexSecret(secret, derivationPath)];
});
});
};
BaseEthereumProtocol.prototype.getExtendedPrivateKeyFromMnemonic = function (mnemonic, derivationPath, password) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error('extended private key support for ether not implemented');
});
});
};
BaseEthereumProtocol.prototype.getPublicKeyFromHexSecret = function (secret, derivationPath) {
return __awaiter(this, void 0, void 0, function () {
var ethereumNode;
return __generator(this, function (_a) {
ethereumNode = bitcoinJS.HDNode.fromSeedHex(secret, this.network);
return [2 /*return*/, ethereumNode.derivePath(derivationPath).neutered().getPublicKeyBuffer().toString('hex')];
});
});
};
BaseEthereumProtocol.prototype.getPrivateKeyFromHexSecret = function (secret, derivationPath) {
return __awaiter(this, void 0, void 0, function () {
var ethereumNode;
return __generator(this, function (_a) {
ethereumNode = bitcoinJS.HDNode.fromSeedHex(secret, this.network);
return [2 /*return*/, ethereumNode.derivePath(derivationPath).keyPair.d.toBuffer(32)];
});
});
};
BaseEthereumProtocol.prototype.getExtendedPrivateKeyFromHexSecret = function (secret, derivationPath) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new Error('extended private key support for ether not implemented');
});
});
};
BaseEthereumProtocol.prototype.getAddressFromPublicKey = function (publicKey) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (typeof publicKey === 'string') {
// TODO: Types
return [2 /*return*/, ethUtil.toChecksumAddress(ethUtil.pubToAddress(Buffer.from(publicKey, 'hex'), true).toString('hex'))];
}
// TODO: Types
return [2 /*return*/, ethUtil.toChecksumAddress(ethUtil.pubToAddress(publicKey, true).toString('hex'))];
});
});
};
BaseEthereumProtocol.prototype.getAddressesFromPublicKey = 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*/, [address]];
}
});
});
};
BaseEthereumProtocol.prototype.getAddressFromExtendedPublicKey = function (extendedPublicKey, visibilityDerivationIndex, addressDerivationIndex) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.getAddressFromPublicKey(bitcoinJS.HDNode.fromBase58(extendedPublicKey, this.network)
.derive(visibilityDerivationIndex)
.derive(addressDerivationIndex)
.getPublicKeyBuffer()
.toString('hex'))];
});
});
};
BaseEthereumProtocol.prototype.getAddressesFromExtendedPublicKey = function (extendedPublicKey, visibilityDerivationIndex, addressCount, offset) {
var _this = this;
var node = bitcoinJS.HDNode.fromBase58(extendedPublicKey, this.network);
var generatorArray = [addressCount].map(function (x, i) { return i + offset; });
return Promise.all(generatorArray.map(function (x) {
return _this.getAddressFromPublicKey(node.derive(visibilityDerivationIndex).derive(x).getPublicKeyBuffer().toString('hex'));
}));
};
BaseEthereumProtocol.prototype.signWithExtendedPrivateKey = function (extendedPrivateKey, transaction) {
return Promise.reject('extended private key signing for ether not implemented');
};
BaseEthereumProtocol.prototype.signWithPrivateKey = function (privateKey, transaction) {
return __awaiter(this, void 0, void 0, function () {
var tx;
return __generator(this, function (_a) {
if (!transaction.value.startsWith('0x')) {
transaction.value = utils_1.EthereumUtils.toHex(parseInt(transaction.value, 10));
}
tx = new EthereumTransaction(transaction);
tx.sign(privateKey);
return [2 /*return*/, tx.serialize().toString('hex')];
});
});
};
BaseEthereumProtocol.prototype.getTransactionDetails = function (unsignedTx) {
return __awaiter(this, void 0, void 0, function () {
var transaction, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
transaction = unsignedTx.transaction;
_a = {};
return [4 /*yield*/, this.getAddressFromPublicKey(unsignedTx.publicKey)];
case 1: return [2 /*return*/, [
(_a.from = [_b.sent()],
_a.to = [transaction.to],
_a.amount = new bignumber_1.BigNumber(transaction.value).toString(10),
_a.fee = new bignumber_1.BigNumber(transaction.gasLimit).multipliedBy(new bignumber_1.BigNumber(transaction.gasPrice)).toString(10),
_a.protocolIdentifier = this.identifier,
_a.network = this.options.network,
_a.isInbound = false,
_a.data = transaction.data,
_a.transactionDetails = unsignedTx,
_a)
]];
}
});
});
};
BaseEthereumProtocol.prototype.getTransactionDetailsFromSigned = function (transaction) {
return __awaiter(this, void 0, void 0, function () {
var ethTx, hexValue, hexGasPrice, hexGasLimit, hexNonce;
return __generator(this, function (_a) {
ethTx = new EthereumTransaction(transaction.transaction);
hexValue = ethTx.value.toString('hex') || '0x0';
hexGasPrice = ethTx.gasPrice.toString('hex') || '0x0';
hexGasLimit = ethTx.gasLimit.toString('hex') || '0x0';
hexNonce = ethTx.nonce.toString('hex') || '0x0';
return [2 /*return*/, [
{
from: [ethUtil.toChecksumAddress("0x" + ethTx.from.toString('hex'))],
to: [ethUtil.toChecksumAddress("0x" + ethTx.to.toString('hex'))],
amount: new bignumber_1.BigNumber(parseInt(hexValue, 16)).toString(10),
fee: new bignumber_1.BigNumber(parseInt(hexGasLimit, 16)).multipliedBy(new bignumber_1.BigNumber(parseInt(hexGasPrice, 16))).toString(10),
protocolIdentifier: this.identifier,
network: this.options.network,
isInbound: ethTx.toCreationAddress(),
hash: "0x" + ethTx.hash().toString('hex'),
data: "0x" + ethTx.data.toString('hex'),
extra: {
nonce: parseInt(hexNonce, 16)
},
transactionDetails: transaction.transaction
}
]];
});
});
};
BaseEthereumProtocol.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])];
}
});
});
};
BaseEthereumProtocol.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.fetchBalance(address);
}))];
case 1:
balances = _a.sent();
return [2 /*return*/, balances.reduce(function (a, b) { return a.plus(b); }).toString(10)];
}
});
});
};
BaseEthereumProtocol.prototype.getBalanceOfPublicKeyForSubProtocols = function (publicKey, subProtocols) {
return __awaiter(this, void 0, void 0, function () {
var address, contractAddresses, balances;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
case 1:
address = _a.sent();
contractAddresses = subProtocols.map(function (subProtocol) {
if (subProtocol.subProtocolType === ICoinSubProtocol_1.SubProtocolType.TOKEN && subProtocol.contractAddress) {
return subProtocol.contractAddress;
}
else {
throw Error('can only retrieve balance of ERC20 tokens');
}
});
return [4 /*yield*/, this.options.nodeClient.callBalanceOfOnContracts(contractAddresses, address)];
case 2:
balances = _a.sent();
return [2 /*return*/, contractAddresses.map(function (contractAddresse) { var _a, _b; return _b = (_a = balances[contractAddresse]) === null || _a === void 0 ? void 0 : _a.toFixed(), (_b !== null && _b !== void 0 ? _b : "0"); })];
}
});
});
};
BaseEthereumProtocol.prototype.getBalanceOfExtendedPublicKey = function (extendedPublicKey, offset) {
if (offset === void 0) { offset = 0; }
return Promise.reject('extended public balance for ether not implemented');
};
BaseEthereumProtocol.prototype.getAvailableBalanceOfAddresses = function (addresses) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.getBalanceOfAddresses(addresses)];
});
});
};
BaseEthereumProtocol.prototype.estimateMaxTransactionValueFromExtendedPublicKey = function (extendedPublicKey, recipients, fee) {
return Promise.reject('estimating max value using extended public key not implemented');
};
BaseEthereumProtocol.prototype.estimateFeeDefaultsFromExtendedPublicKey = function (publicKey, recipients, values, data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, Promise.reject('estimating default fees using extended public key not implemented')];
});
});
};
BaseEthereumProtocol.prototype.prepareTransactionFromExtendedPublicKey = function (extendedPublicKey, offset, recipients, values, fee) {
return Promise.reject('extended public tx for ether not implemented');
};
BaseEthereumProtocol.prototype.estimateMaxTransactionValueFromPublicKey = function (publicKey, recipients, fee) {
return __awaiter(this, void 0, void 0, function () {
var balance, balanceWrapper, maxFee, estimatedFeeDefaults, amountWithoutFees;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
case 1:
balance = _a.sent();
balanceWrapper = new bignumber_1.BigNumber(balance);
if (!(fee !== undefined)) return [3 /*break*/, 2];
maxFee = new bignumber_1.BigNumber(fee);
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, this.estimateFeeDefaultsFromPublicKey(publicKey, recipients, [balance])];
case 3:
estimatedFeeDefaults = _a.sent();
maxFee = new bignumber_1.BigNumber(estimatedFeeDefaults.medium).shiftedBy(this.decimals);
if (maxFee.gte(balanceWrapper)) {
maxFee = new bignumber_1.BigNumber(0);
}
_a.label = 4;
case 4:
amountWithoutFees = balanceWrapper.minus(maxFee);
if (amountWithoutFees.isNegative()) {
amountWithoutFees = new bignumber_1.BigNumber(0);
}
return [2 /*return*/, amountWithoutFees.toFixed()];
}
});
});
};
BaseEthereumProtocol.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.options.nodeClient.estimateTransactionGas(address, recipients[0], utils_1.EthereumUtils.toHex(values[0]), undefined, utils_1.EthereumUtils.toHex('21000'))];
case 2:
estimatedGas = _a.sent();
return [4 /*yield*/, this.options.nodeClient.getGasPrice()];
case 3:
gasPrise = _a.sent();
feeStepFactor = new bignumber_1.BigNumber(0.5);
estimatedFee = estimatedGas.times(gasPrise);
lowFee = estimatedFee.minus(estimatedFee.times(feeStepFactor).integerValue(bignumber_1.BigNumber.ROUND_FLOOR));
mediumFee = estimatedFee;
highFee = mediumFee.plus(mediumFee.times(feeStepFactor).integerValue(bignumber_1.BigNumber.ROUND_FLOOR));
return [2 /*return*/, {
low: lowFee.shiftedBy(-this.feeDecimals).toFixed(),
medium: mediumFee.shiftedBy(-this.feeDecimals).toFixed(),
high: highFee.shiftedBy(-this.feeDecimals).toFixed()
}];
}
});
});
};
BaseEthereumProtocol.prototype.prepareTransactionFromPublicKey = function (publicKey, recipients, values, fee, data) {
return __awaiter(this, void 0, void 0, function () {
var wrappedValues, wrappedFee, address, amount, balance, gasLimit, gasPrice, txCount, transaction;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
wrappedValues = values.map(function (value) { return new bignumber_1.BigNumber(value); });
wrappedFee = new bignumber_1.BigNumber(fee);
return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
case 1:
address = _a.sent();
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')];
}
amount = utils_1.EthereumUtils.toHex(wrappedValues[0].toFixed());
return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
case 2:
balance = _a.sent();
return [4 /*yield*/, this.options.nodeClient.estimateTransactionGas(address, recipients[0], amount, undefined, utils_1.EthereumUtils.toHex('21000'))];
case 3:
gasLimit = _a.sent();
gasPrice = wrappedFee.div(gasLimit).integerValue(bignumber_1.BigNumber.ROUND_CEIL);
if (!new bignumber_1.BigNumber(balance).gte(new bignumber_1.BigNumber(wrappedValues[0].plus(wrappedFee)))) return [3 /*break*/, 5];
return [4 /*yield*/, this.options.nodeClient.fetchTransactionCount(address)];
case 4:
txCount = _a.sent();
transaction = {
nonce: utils_1.EthereumUtils.toHex(txCount),
gasLimit: utils_1.EthereumUtils.toHex(gasLimit.toFixed()),
gasPrice: utils_1.EthereumUtils.toHex(gasPrice.toFixed()),
to: recipients[0],
value: amount,
chainId: this.options.network.extras.chainID,
data: '0x'
};
return [2 /*return*/, transaction];
case 5: throw new Error('not enough balance');
}
});
});
};
BaseEthereumProtocol.prototype.broadcastTransaction = function (rawTransaction) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.options.nodeClient.sendSignedTransaction("0x" + rawTransaction)];
});
});
};
BaseEthereumProtocol.prototype.getTransactionsFromExtendedPublicKey = function (extendedPublicKey, limit, cursor) {
return Promise.reject('extended public transaction list for ether not implemented');
};
BaseEthereumProtocol.prototype.getTransactionsFromPublicKey = function (publicKey, limit, cursor) {
if (limit === void 0) { limit = 50; }
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.getTransactionsFromAddresses([address], limit, cursor)];
}
});
});
};
BaseEthereumProtocol.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.fetchTransactions(_this, 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);
});
};
BaseEthereumProtocol.prototype.signMessage = function (message, keypair) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new EthereumCryptoClient_1.EthereumCryptoClient(this).signMessage(message, keypair)];
});
});
};
BaseEthereumProtocol.prototype.verifyMessage = function (message, signature, publicKey) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new EthereumCryptoClient_1.EthereumCryptoClient(this).verifyMessage(message, signature, publicKey)];
});
});
};
BaseEthereumProtocol.prototype.getTransactionStatuses = function (transactionHashes) {
return __awaiter(this, void 0, void 0, function () {
var statusPromises;
var _this = this;
return __generator(this, function (_a) {
statusPromises = transactionHashes.map(function (txHash) {
return _this.options.nodeClient.getTransactionStatus(txHash);
});
return [2 /*return*/, Promise.all(statusPromises)];
});
});
};
return BaseEthereumProtocol;
}());
exports.BaseEthereumProtocol = BaseEthereumProtocol;
//# sourceMappingURL=BaseEthereumProtocol.js.map