UNPKG

@pokt-network/pocket-js

Version:

Pocket-js core package with the main functionalities to interact with the Pocket Network.

377 lines 19.1 kB
"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 }); exports.TransactionSender = void 0; var msgs_1 = require("./models/msgs"); var models_1 = require("./models/"); var models_2 = require("../keybase/models"); var __1 = require(".."); var tx_encoder_factory_1 = require("./factory/tx-encoder-factory"); var proto_1 = require("./models/proto"); var factory_1 = require("./factory"); var TransactionSender = /** @class */ (function () { /** * Constructor for this class. Requires either an unlockedAccount or txSigner * @param {Pocket} pocket - Pocket instance * @param {UnlockedAccount} unlockedAccount - Unlocked account * @param {TransactionSigner} txSigner - Transaction signer */ function TransactionSender(pocket, unlockedAccount, txSigner, offlineMode) { this.unlockedAccount = unlockedAccount; this.txSigner = txSigner; this.pocket = pocket; this.offlineMode = offlineMode; if (!this.offlineMode && this.unlockedAccount === undefined && this.txSigner === undefined) { throw new Error("Need to define unlockedAccount or txSigner"); } } /** * Signs and creates a transaction object that can be submitted to the network given the parameters and called upon Msgs. * Will empty the msg list after succesful creation * @param {string} chainID - The chainID of the network to be sent to * @param {string} fee - The amount to pay as a fee for executing this transaction * @param {CoinDenom | undefined} feeDenom - The denomination of the fee amount * @param {string | undefined} memo - The memo field for this account * @returns {Promise<RawTxResponse | RpcError>} - A Raw transaction Response object or Rpc error. * @memberof TransactionSender */ TransactionSender.prototype.createTransaction = function (chainID, fee, feeDenom, memo, signature) { return __awaiter(this, void 0, void 0, function () { var rpcError, entropy, signer, txSignature, bytesToSign, addressHex, encodedTxBytes, txRequest, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 6, , 7]); if (this.txMsgError !== undefined) { rpcError = __1.RpcError.fromError(this.txMsgError); this.txMsg = undefined; this.txMsgError = undefined; return [2 /*return*/, rpcError]; } if (this.txMsg === undefined) { return [2 /*return*/, new __1.RpcError("0", "No messages configured for this transaction")]; } entropy = Number(BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)).toString()).toString(); signer = tx_encoder_factory_1.TxEncoderFactory.createEncoder(entropy, chainID, this.txMsg, fee, feeDenom, memo, this.pocket.configuration.useLegacyTxCodec); txSignature = void 0; if (!!signature) return [3 /*break*/, 4]; bytesToSign = signer.marshalStdSignDoc(); if (!__1.typeGuard(this.unlockedAccount, models_2.UnlockedAccount)) return [3 /*break*/, 2]; return [4 /*yield*/, this.signWithUnlockedAccount(bytesToSign, this.unlockedAccount)]; case 1: txSignature = _a.sent(); return [3 /*break*/, 3]; case 2: if (this.txSigner !== undefined) { txSignature = this.signWithTrasactionSigner(bytesToSign, this.txSigner); } else { return [2 /*return*/, new __1.RpcError("0", "No account or TransactionSigner specified")]; } _a.label = 3; case 3: return [3 /*break*/, 5]; case 4: txSignature = signature; _a.label = 5; case 5: if (!__1.typeGuard(txSignature, models_1.TxSignature)) { return [2 /*return*/, new __1.RpcError("0", "Error generating signature for transaction")]; } addressHex = __1.addressFromPublickey(txSignature.pubKey); encodedTxBytes = signer.marshalStdTx(txSignature); // Clean message and error this.txMsg = undefined; this.txMsgError = undefined; txRequest = new __1.RawTxRequest(addressHex.toString("hex"), encodedTxBytes.toString("hex")); return [2 /*return*/, txRequest]; case 6: error_1 = _a.sent(); return [2 /*return*/, __1.RpcError.fromError(error_1)]; case 7: return [2 /*return*/]; } }); }); }; /** * Creates an unsigned transaction hex that can be signed with a valid ed25519 private key * @param {string} chainID - The chainID of the network to be sent to * @param {string} fee - The amount to pay as a fee for executing this transaction * @param {CoinDenom | undefined} feeDenom - The denomination of the fee amount * @param {string | undefined} memo - The memo field for this account * @param {string} entropy - The entropy for this tx * @returns {Promise<{ bytesToSign: string, stdTxMsgObj: string } | RpcError>} - bytes to sign and the stringified stxTxMsgObj * @memberof TransactionSender */ TransactionSender.prototype.createUnsignedTransaction = function (chainID, fee, entropy, feeDenom, memo) { try { if (this.txMsgError !== undefined) { var rpcError = __1.RpcError.fromError(this.txMsgError); this.txMsg = undefined; this.txMsgError = undefined; return rpcError; } if (this.txMsg === undefined) { return new __1.RpcError("0", "No messages configured for this transaction"); } // This needs to be strinfigied so it can be stored offline, // since it's required to sign the transaction. var stdTxMsgObj = proto_1.Any.toJSON(this.txMsg.toStdTxMsgObj()); var unsignedTxBytes = factory_1.ProtoTxEncoder.marshalStdSignDoc(chainID, entropy, fee, stdTxMsgObj, memo, feeDenom); // Clean message and error this.txMsg = undefined; this.txMsgError = undefined; return { bytesToSign: unsignedTxBytes.toString('hex'), stdTxMsgObj: JSON.stringify(stdTxMsgObj) }; } catch (error) { return __1.RpcError.fromError(error); } }; /** * Signs and submits a transaction to the network given the parameters for each Msg in the Msg list. Will empty the msg list after submission attempt * @param {string} chainID - The chainID of the network to be sent to * @param {string} fee - The amount to pay as a fee for executing this transaction * @param {CoinDenom | undefined} feeDenom - The denomination of the fee amount * @param {string | undefined} memo - The memo field for this account * @param {number | undefined} timeout - Request timeout * @returns {Promise<RawTxResponse | RpcError>} - A Raw transaction Response object or Rpc error. * @memberof TransactionSender */ TransactionSender.prototype.submit = function (chainID, fee, feeDenom, memo, timeout) { return __awaiter(this, void 0, void 0, function () { var rawTxRequestOrError, rawTxRequest, response, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, this.createTransaction(chainID, fee, feeDenom, memo)]; case 1: rawTxRequestOrError = _a.sent(); if (!__1.typeGuard(rawTxRequestOrError, __1.RawTxRequest)) { return [2 /*return*/, rawTxRequestOrError]; } rawTxRequest = rawTxRequestOrError; // Clean message and error this.txMsg = undefined; this.txMsgError = undefined; return [4 /*yield*/, this.pocket.rpc().client.rawtx(rawTxRequest.address, rawTxRequest.txHex, timeout)]; case 2: response = _a.sent(); return [2 /*return*/, response]; case 3: error_2 = _a.sent(); return [2 /*return*/, __1.RpcError.fromError(error_2)]; case 4: return [2 /*return*/]; } }); }); }; /** * Adds a MsgSend TxMsg for this transaction * @param {string} fromAddress - Origin address * @param {string} toAddress - Destination address * @param {string} amount - Amount to be sent, needs to be a valid number greater than 0 * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.send = function (fromAddress, toAddress, amount) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgSend(fromAddress, toAddress, amount); else this.txMsg = new msgs_1.MsgProtoSend(fromAddress, toAddress, amount); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgAppStake TxMsg for this transaction * @param {string} appPubKey - Application Public Key * @param {string[]} chains - Network identifier list to be requested by this app * @param {string} amount - the amount to stake, must be greater than 0 * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.appStake = function (appPubKey, chains, amount) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgAppStake(Buffer.from(appPubKey, "hex"), chains, amount); else this.txMsg = new msgs_1.MsgProtoAppStake(Buffer.from(appPubKey, "hex"), chains, amount); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgBeginAppUnstake TxMsg for this transaction * @param {string} address - Address of the Application to unstake for * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.appUnstake = function (address) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgAppUnstake(address); else this.txMsg = new msgs_1.MsgProtoAppUnstake(address); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgAppUnjail TxMsg for this transaction * @param {string} address - Address of the Application to unjail * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.appUnjail = function (address) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgAppUnjail(address); else this.txMsg = new msgs_1.MsgProtoAppUnjail(address); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgAppStake TxMsg for this transaction * @param {string} nodePubKey - Node Public key * @param {string[]} chains - Network identifier list to be serviced by this node * @param {string} amount - the amount to stake, must be greater than 0 * @param {URL} serviceURL - Node service url * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.nodeStake = function (nodePubKey, outputAddress, chains, amount, serviceURL) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgNodeStake(Buffer.from(nodePubKey, "hex"), chains, amount, serviceURL); else this.txMsg = new msgs_1.MsgProtoNodeStakeTx(Buffer.from(nodePubKey, "hex"), Buffer.from(outputAddress, "hex"), chains, amount, serviceURL); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgBeginUnstake TxMsg for this transaction * @param {string} address - Address of the Node to unstake for * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.nodeUnstake = function (nodeAddress, signerAddress) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new models_1.MsgNodeUnstake(nodeAddress); else this.txMsg = new msgs_1.MsgProtoNodeUnstake(nodeAddress, signerAddress); } catch (error) { this.txMsgError = error; } return this; }; /** * Adds a MsgUnjail TxMsg for this transaction * @param {string} nodeAddress - Address of the Node to unjail * @returns {ITransactionSender} - A transaction sender. * @memberof TransactionSender */ TransactionSender.prototype.nodeUnjail = function (nodeAddress, signerAddress) { try { if (this.pocket.configuration.useLegacyTxCodec) this.txMsg = new msgs_1.MsgNodeUnjailTx(nodeAddress); else this.txMsg = new msgs_1.MsgProtoNodeUnjail(nodeAddress, signerAddress); } catch (error) { this.txMsgError = error; } return this; }; /** * Signs using the unlockedAccount attribute of this class * @param {Buffer} bytesToSign - Bytes to be signed * @param {UnlockedAccount} unlockedAccount - Unlocked account for signing * @returns {TxSignature | Error} - A transaction signature or error. * @memberof TransactionSender */ TransactionSender.prototype.signWithUnlockedAccount = function (bytesToSign, unlockedAccount) { return __awaiter(this, void 0, void 0, function () { var signatureOrError; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, __1.Keybase.signWith(unlockedAccount.privateKey, bytesToSign)]; case 1: signatureOrError = _a.sent(); if (__1.typeGuard(signatureOrError, Error)) { return [2 /*return*/, signatureOrError]; } return [2 /*return*/, new models_1.TxSignature(unlockedAccount.publicKey, signatureOrError)]; } }); }); }; /** * Signs using the txSigner attribute of this class * @param {Buffer} bytesToSign - Bytes to sign * @param {TransactionSigner} txSigner - Transaction signer * @returns {TxSignature | Error} - A transaction signature or error. * @memberof TransactionSender */ TransactionSender.prototype.signWithTrasactionSigner = function (bytesToSign, txSigner) { var transactionSignatureOrError = txSigner(bytesToSign); if (__1.typeGuard(transactionSignatureOrError, Error)) { return transactionSignatureOrError; } var txSignature = transactionSignatureOrError; return new models_1.TxSignature(txSignature.publicKey, txSignature.signature); }; return TransactionSender; }()); exports.TransactionSender = TransactionSender; //# sourceMappingURL=transaction-sender.js.map