UNPKG

@abcpros/bitcore-wallet-service

Version:
429 lines 23.2 kB
"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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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 }); exports.XecChain = void 0; var crypto_wallet_core_1 = require("@abcpros/crypto-wallet-core"); var bignumber_js_1 = require("bignumber.js"); var chronik_client_1 = require("chronik-client"); var lodash_1 = __importStar(require("lodash")); var btc_1 = require("../btc"); var config = require('../../../config'); var Errors = require('../../errors/errordefinitions'); var Common = require('../../common'); var Utils = Common.Utils; var BCHJS = require('@abcpros/xpi-js'); var bchjs = new BCHJS({ restURL: '' }); var ecashaddr = require('ecashaddrjs'); var protocolPrefix = { livenet: 'ecash', testnet: 'ectest' }; var XecChain = (function (_super) { __extends(XecChain, _super); function XecChain() { var _a, _b, _c, _d; var _this = _super.call(this, crypto_wallet_core_1.BitcoreLibXec) || this; _this.sizeEstimationMargin = (_b = (_a = config.bch) === null || _a === void 0 ? void 0 : _a.sizeEstimationMargin) !== null && _b !== void 0 ? _b : 0.01; _this.inputSizeEstimationMargin = (_d = (_c = config.bch) === null || _c === void 0 ? void 0 : _c.inputSizeEstimationMargin) !== null && _d !== void 0 ? _d : 2; _this.chronikClient = new chronik_client_1.ChronikClient(config.supportToken.xec.chronikClientUrl); return _this; } XecChain.prototype.convertAddressToScriptPayload = function (address) { try { var protoXEC = protocolPrefix.livenet; var protoAddr = protoXEC + ':' + address; var _a = ecashaddr.decode(protoAddr), prefix = _a.prefix, type = _a.type, hash = _a.hash; var cashAddress = ecashaddr.encode('bitcoincash', type, hash); return bchjs.Address.toHash160(cashAddress); } catch (_b) { return ''; } }; XecChain.prototype.getChronikClient = function () { return this.chronikClient; }; XecChain.prototype.getTokenInfo = function (tokenId) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; return __awaiter(this, void 0, void 0, function () { var tx; return __generator(this, function (_k) { switch (_k.label) { case 0: return [4, this.chronikClient.tx(tokenId)]; case 1: tx = _k.sent(); return [2, { coin: 'xec', id: ((_a = tx.slpTxData) === null || _a === void 0 ? void 0 : _a.slpMeta.tokenId) || '', symbol: ((_c = (_b = tx.slpTxData) === null || _b === void 0 ? void 0 : _b.genesisInfo) === null || _c === void 0 ? void 0 : _c.tokenTicker) || '', name: ((_e = (_d = tx.slpTxData) === null || _d === void 0 ? void 0 : _d.genesisInfo) === null || _e === void 0 ? void 0 : _e.tokenName) || '', documentUri: ((_g = (_f = tx.slpTxData) === null || _f === void 0 ? void 0 : _f.genesisInfo) === null || _g === void 0 ? void 0 : _g.tokenDocumentUrl) || '', documentHash: ((_j = (_h = tx.slpTxData) === null || _h === void 0 ? void 0 : _h.genesisInfo) === null || _j === void 0 ? void 0 : _j.tokenDocumentHash) || '', decimals: tx.slpTxData && tx.slpTxData.genesisInfo && lodash_1.isNumber(tx.slpTxData.genesisInfo.decimals) ? tx.slpTxData.genesisInfo.decimals : NaN }]; } }); }); }; XecChain.prototype.sendToken = function (wallet, mnemonic, tokenId, token, TOKENQTY, etokenAddress) { return __awaiter(this, void 0, void 0, function () { var tokenInfo, rootSeed, masterHDNode, rootPath, account, change, cashAddress, slpAddress, utxos, xecUtxos, tokenUtxos, bchUtxo, transactionBuilder, originalAmount, i, txFee, remainder, slpSendObj, slpData, _a, prefix, type, hash, cashAdr, redeemScript, childIndex, changeCash, keyPairCash, i, thisUtxo, childIndex_1, changeToken, keyPairToken, tx, hex, txid, e_1; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4, this.getTokenInfo(tokenId)]; case 1: tokenInfo = _b.sent(); return [4, bchjs.Mnemonic.toSeed(mnemonic)]; case 2: rootSeed = _b.sent(); masterHDNode = bchjs.HDNode.fromSeed(rootSeed); rootPath = wallet.getRootPath() ? wallet.getRootPath() : "m/44'/1899'/0'"; account = bchjs.HDNode.derivePath(masterHDNode, rootPath); change = bchjs.HDNode.derivePath(account, '0/0'); cashAddress = bchjs.HDNode.toCashAddress(change); slpAddress = bchjs.HDNode.toSLPAddress(change); _b.label = 3; case 3: _b.trys.push([3, 7, , 8]); return [4, this.getUtxosToken(wallet)]; case 4: utxos = _b.sent(); if (utxos.length === 0) throw new Error('No UTXOs to spend! Exiting.'); xecUtxos = lodash_1.default.filter(utxos, function (item) { return item.isNonSLP; }); if (xecUtxos.length === 0) { throw new Error('Wallet does not have a BCH UTXO to pay miner fees.'); } return [4, this.getTokenUtxos(utxos, tokenInfo)]; case 5: tokenUtxos = _b.sent(); if (tokenUtxos.length === 0) { throw new Error('No token UTXOs for the specified token could be found.'); } bchUtxo = this.findBiggestUtxo(xecUtxos); transactionBuilder = void 0; transactionBuilder = new bchjs.TransactionBuilder(); originalAmount = bchUtxo.value; transactionBuilder.addInput(bchUtxo.txid, bchUtxo.outIdx); for (i = 0; i < tokenUtxos.length; i++) { transactionBuilder.addInput(tokenUtxos[i].txid, tokenUtxos[i].outIdx); } txFee = 250; remainder = originalAmount - txFee - 546 * 2; if (remainder < 1) { throw new Error('Selected UTXO does not have enough satoshis'); } TOKENQTY = TOKENQTY / Math.pow(10, tokenInfo.decimals); TOKENQTY = lodash_1.default.floor(TOKENQTY, tokenInfo.decimals); slpSendObj = bchjs.SLP.TokenType1.generateSendOpReturn(tokenUtxos, TOKENQTY); slpData = slpSendObj.script; transactionBuilder.addOutput(slpData, 0); if (!!etokenAddress) { _a = ecashaddr.decode(etokenAddress), prefix = _a.prefix, type = _a.type, hash = _a.hash; cashAdr = ecashaddr.encode('bitcoincash', type, hash); transactionBuilder.addOutput(bchjs.SLP.Address.toLegacyAddress(cashAdr), 546); } else { transactionBuilder.addOutput(bchjs.SLP.Address.toLegacyAddress(cashAddress), 546); } if (slpSendObj.outputs > 1) { transactionBuilder.addOutput(bchjs.SLP.Address.toLegacyAddress(slpAddress), 546); } transactionBuilder.addOutput(bchjs.Address.toLegacyAddress(cashAddress), remainder); redeemScript = void 0; childIndex = bchUtxo.addressInfo.path.replace(/m\//gm, ''); changeCash = bchjs.HDNode.derivePath(account, childIndex); keyPairCash = bchjs.HDNode.toKeyPair(changeCash); transactionBuilder.sign(0, keyPairCash, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, originalAmount); for (i = 0; i < tokenUtxos.length; i++) { thisUtxo = tokenUtxos[i]; childIndex_1 = thisUtxo.addressInfo.path.replace(/m\//gm, ''); changeToken = bchjs.HDNode.derivePath(account, childIndex_1); keyPairToken = bchjs.HDNode.toKeyPair(changeToken); transactionBuilder.sign(1 + i, keyPairToken, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, thisUtxo.value); } tx = transactionBuilder.build(); hex = tx.toHex(); return [4, this.broadcastRaw(wallet, hex, true).catch(function (e) { throw e; })]; case 6: txid = _b.sent(); return [2, txid]; case 7: e_1 = _b.sent(); throw e_1; case 8: return [2]; } }); }); }; XecChain.prototype.burnToken = function (wallet, mnemonic, tokenId, TOKENQTY, splitTxId) { return __awaiter(this, void 0, void 0, function () { var tokenInfo, rootSeed, masterHDNode, rootPath, account, change, cashAddress, slpAddress, utxos, xecUtxos, tokenUtxos, tokenUtxoSelected, bchUtxo, slpData, transactionBuilder, originalAmount, byteCount, remainder, redeemScript, childIndex, changeCash, keyPairCash, thisUtxo, childIndex2, changeToken, keyPairToken, tx, hex, txid; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, this.getTokenInfo(tokenId)]; case 1: tokenInfo = _a.sent(); return [4, bchjs.Mnemonic.toSeed(mnemonic)]; case 2: rootSeed = _a.sent(); masterHDNode = bchjs.HDNode.fromSeed(rootSeed); rootPath = wallet.getRootPath() ? wallet.getRootPath() : "m/44'/1899'/0'"; account = bchjs.HDNode.derivePath(masterHDNode, rootPath); change = bchjs.HDNode.derivePath(account, '0/0'); cashAddress = bchjs.HDNode.toCashAddress(change); slpAddress = bchjs.HDNode.toSLPAddress(change); return [4, this.getUtxosToken(wallet)]; case 3: utxos = _a.sent(); if (utxos.length === 0) throw new Error('No UTXOs to spend! Exiting.'); xecUtxos = lodash_1.default.filter(utxos, function (item) { return item.isNonSLP; }); if (xecUtxos.length === 0) { throw new Error('Wallet does not have a BCH UTXO to pay miner fees.'); } return [4, this.getTokenUtxos(utxos, tokenInfo)]; case 4: tokenUtxos = _a.sent(); if (tokenUtxos.length === 0) { throw new Error('No token UTXOs for the specified token could be found.'); } tokenUtxoSelected = tokenUtxos.find(function (utxo) { return utxo.txid === splitTxId; }); bchUtxo = this.findBiggestUtxo(xecUtxos); TOKENQTY = TOKENQTY / Math.pow(10, tokenInfo.decimals); TOKENQTY = lodash_1.default.floor(TOKENQTY, tokenInfo.decimals); slpData = this.buildBurnOpReturn(tokenInfo.id, new bignumber_js_1.BigNumber(TOKENQTY).times(Math.pow(10, tokenInfo.decimals))); transactionBuilder = new bchjs.TransactionBuilder(); originalAmount = bchUtxo.value; transactionBuilder.addInput(bchUtxo.txid, bchUtxo.outIdx); transactionBuilder.addInput(tokenUtxoSelected.txid, tokenUtxoSelected.outIdx); byteCount = bchjs.BitcoinCash.getByteCount({ P2PKH: 2 }, { P2PKH: 2 }); byteCount += slpData.length; remainder = originalAmount - byteCount; if (remainder < 0) { throw new Error('Selected UTXO does not have enough satoshis'); } transactionBuilder.addOutput(slpData, 0); if (remainder > 546) { transactionBuilder.addOutput(bchjs.Address.toLegacyAddress(cashAddress), remainder); } childIndex = bchUtxo.addressInfo.path.replace(/m\//gm, ''); changeCash = bchjs.HDNode.derivePath(account, childIndex); keyPairCash = bchjs.HDNode.toKeyPair(changeCash); transactionBuilder.sign(0, keyPairCash, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, originalAmount); thisUtxo = tokenUtxoSelected; childIndex2 = thisUtxo.addressInfo.path.replace(/m\//gm, ''); changeToken = bchjs.HDNode.derivePath(account, childIndex2); keyPairToken = bchjs.HDNode.toKeyPair(changeToken); transactionBuilder.sign(1, keyPairToken, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, thisUtxo.value); tx = transactionBuilder.build(); hex = tx.toHex(); return [4, this.broadcastRaw(wallet, hex, true)]; case 5: txid = _a.sent(); return [2, txid]; } }); }); }; XecChain.prototype.findBiggestUtxo = function (utxos) { var largestAmount = 0; var largestIndex = 0; for (var i = 0; i < utxos.length; i++) { var thisUtxo = utxos[i]; if (thisUtxo.value > largestAmount) { largestAmount = thisUtxo.value; largestIndex = i; } } return utxos[largestIndex]; }; XecChain.prototype.getTokenUtxos = function (utxos, tokenInfo) { var tokenUtxos = []; lodash_1.default.forEach(utxos, function (item) { var slpMeta = lodash_1.default.get(item, 'slpMeta', undefined); if (item.amountToken && slpMeta.tokenId && slpMeta.tokenId === tokenInfo.id && slpMeta.txType != 'MINT') { var tokenUtxo = { addressInfo: item.addressInfo, txid: item.txid, outIdx: item.outIdx, value: item.value, decimals: tokenInfo.decimals, tokenId: tokenInfo.id, tokenQty: item.amountToken / Math.pow(10, tokenInfo.decimals), amountToken: item.amountToken }; tokenUtxos.push(tokenUtxo); } }); return tokenUtxos; }; XecChain.prototype.broadcastRaw = function (wallet, raw, ischronik) { return new Promise(function (resolve, reject) { wallet.broadcastRawTx({ rawTx: raw, network: 'livenet', coin: wallet.credentials.coin, ischronik: ischronik }, function (err, txid) { if (err || !txid) return reject(err ? err : 'No Tokens'); return resolve(txid); }); }); }; XecChain.prototype.getUtxosToken = function (wallet) { return new Promise(function (resolve, reject) { wallet.getUtxosToken({ coin: 'xec' }, function (err, resp) { if (err || !resp || !resp.length) reject(err ? err : 'No UTXOs'); resolve(resp); }); }); }; XecChain.prototype.convertFeePerKb = function (p, feePerKb) { return [p, Utils.strip(feePerKb * 1e2)]; }; XecChain.prototype.getSizeSafetyMargin = function (opts) { return 0; }; XecChain.prototype.getInputSizeSafetyMargin = function (opts) { return 0; }; XecChain.prototype.validateAddress = function (wallet, inaddr, opts) { var A = crypto_wallet_core_1.BitcoreLibXec.Address; var addr = {}; try { addr = new A(inaddr); } catch (ex) { throw Errors.INVALID_ADDRESS; } if (addr.network.toString() != wallet.network) { throw Errors.INCORRECT_ADDRESS_NETWORK; } return; }; XecChain.prototype.pushdata = function (buf) { if (buf.length === 0) { return Buffer.from([0x4c, 0x00]); } else if (buf.length < 0x4e) { return Buffer.concat([Buffer.from([buf.length]), buf]); } else if (buf.length < 0xff) { return Buffer.concat([Buffer.from([0x4c, buf.length]), buf]); } else if (buf.length < 0xffff) { var tmp = Buffer.allocUnsafe(2); tmp.writeUInt16LE(buf.length, 0); return Buffer.concat([Buffer.from([0x4d]), tmp, buf]); } else if (buf.length < 0xffffffff) { var tmp = Buffer.allocUnsafe(4); tmp.writeUInt32LE(buf.length, 0); return Buffer.concat([Buffer.from([0x4e]), tmp, buf]); } else { throw new Error('does not support bigger pushes yet'); } }; XecChain.prototype.BNToInt64BE = function (bn) { if (!bn.isInteger()) { throw new Error('bn not an integer'); } if (!bn.isPositive()) { throw new Error('bn not positive integer'); } var h = bn.toString(16); if (h.length > 16) { throw new Error('bn outside of range'); } return Buffer.from(h.padStart(16, '0'), 'hex'); }; XecChain.prototype.buildBurnOpReturn = function (tokenId, burnQuantity) { var tokenIdHex = Buffer.from(tokenId, 'hex'); var buf = Buffer.concat([ Buffer.from([0x6a]), this.pushdata(Buffer.from('SLP\0')), this.pushdata(Buffer.from([0x01])), this.pushdata(Buffer.from('BURN')), this.pushdata(tokenIdHex), this.pushdata(this.BNToInt64BE(burnQuantity)) ]); return buf; }; return XecChain; }(btc_1.BtcChain)); exports.XecChain = XecChain; //# sourceMappingURL=index.js.map