UNPKG

@taquito/taquito

Version:

High level functionality that builds upon the other packages in the Tezos Typescript Library Suite.

255 lines 12.4 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 __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OperationEmitter = void 0; const rpc_1 = require("@taquito/rpc"); const constants_1 = require("../constants"); const error_1 = require("../error"); const operation_errors_1 = require("./operation-errors"); const types_1 = require("./types"); const core_1 = require("@taquito/core"); class OperationEmitter { constructor(context) { this.context = context; } get rpc() { return this.context.rpc; } get signer() { return this.context.signer; } isRevealOpNeeded(op, pkh) { return __awaiter(this, void 0, void 0, function* () { return !(yield this.isAccountRevealRequired(pkh)) || !this.isRevealRequiredForOpType(op) ? false : true; }); } isAccountRevealRequired(publicKeyHash) { return __awaiter(this, void 0, void 0, function* () { return !(yield this.context.readProvider.isAccountRevealed(publicKeyHash, 'head')); }); } isRevealRequiredForOpType(op) { let opRequireReveal = false; for (const operation of op) { if (types_1.isOpRequireReveal(operation)) { opRequireReveal = true; } } return opRequireReveal; } // Originally from sotez (Copyright (c) 2018 Andrew Kishino) prepareOperation({ operation, source }, pkh) { return __awaiter(this, void 0, void 0, function* () { const counters = {}; let ops = []; const blockHashPromise = this.context.readProvider.getBlockHash('head~2'); const blockProtoPromise = this.context.readProvider.getNextProtocol('head'); if (Array.isArray(operation)) { ops = [...operation]; } else { ops = [operation]; } // Implicit account who emit the operation const publicKeyHash = pkh ? pkh : yield this.signer.publicKeyHash(); let counterPromise = Promise.resolve(undefined); // initializes a currentVotingPeriod if the operation is a ballot op let currentVotingPeriodPromise = Promise.resolve(undefined); ops.find((op) => __awaiter(this, void 0, void 0, function* () { if (op.kind === 'ballot' || op.kind === 'proposals') { try { currentVotingPeriodPromise = this.rpc.getCurrentPeriod(); } catch (e) { throw new error_1.RPCResponseError(`Failed to get the current voting period index: ${JSON.stringify(e)}`); } } })); for (let i = 0; i < ops.length; i++) { if (types_1.isOpRequireReveal(ops[i]) || ops[i].kind === 'reveal') { counterPromise = this.context.readProvider.getCounter(publicKeyHash, 'head'); break; } } const [hash, protocol, headCounter, currentVotingPeriod] = yield Promise.all([ blockHashPromise, blockProtoPromise, counterPromise, currentVotingPeriodPromise, ]); const counter = parseInt(headCounter || '0', 10); if (!counters[publicKeyHash] || counters[publicKeyHash] < counter) { counters[publicKeyHash] = counter; } const getFee = (op) => { const opCounter = ++counters[publicKeyHash]; return { counter: `${opCounter}`, fee: typeof op.fee === 'undefined' ? '0' : `${op.fee}`, gas_limit: typeof op.gas_limit === 'undefined' ? '0' : `${op.gas_limit}`, storage_limit: typeof op.storage_limit === 'undefined' ? '0' : `${op.storage_limit}`, }; }; const getSource = (op) => { return { source: typeof op.source === 'undefined' ? source || publicKeyHash : op.source, }; }; const constructOps = (cOps) => cOps.map((op) => { switch (op.kind) { case rpc_1.OpKind.ACTIVATION: case rpc_1.OpKind.DRAIN_DELEGATE: return Object.assign({}, op); case rpc_1.OpKind.ORIGINATION: return Object.assign(Object.assign(Object.assign(Object.assign({}, op), { balance: typeof op.balance !== 'undefined' ? `${op.balance}` : '0' }), getSource(op)), getFee(op)); case rpc_1.OpKind.TRANSACTION: { const cops = Object.assign(Object.assign(Object.assign(Object.assign({}, op), { amount: typeof op.amount !== 'undefined' ? `${op.amount}` : '0' }), getSource(op)), getFee(op)); if (cops.source.toLowerCase().startsWith('kt1')) { throw new core_1.DeprecationError(`KT1 addresses are not supported as source since ${constants_1.Protocols.PsBabyM1}`); } return cops; } case rpc_1.OpKind.REVEAL: case rpc_1.OpKind.DELEGATION: case rpc_1.OpKind.REGISTER_GLOBAL_CONSTANT: case rpc_1.OpKind.UPDATE_CONSENSUS_KEY: case rpc_1.OpKind.SMART_ROLLUP_ADD_MESSAGES: case rpc_1.OpKind.SMART_ROLLUP_ORIGINATE: return Object.assign(Object.assign(Object.assign({}, op), getSource(op)), getFee(op)); case rpc_1.OpKind.TRANSFER_TICKET: return Object.assign(Object.assign(Object.assign(Object.assign({}, op), { ticket_amount: `${op.ticket_amount}` }), getSource(op)), getFee(op)); case rpc_1.OpKind.INCREASE_PAID_STORAGE: return Object.assign(Object.assign(Object.assign(Object.assign({}, op), { amount: `${op.amount}` }), getSource(op)), getFee(op)); case rpc_1.OpKind.BALLOT: if (currentVotingPeriod === undefined) { throw new error_1.RPCResponseError(`Failed to get the current voting period index`); } return Object.assign(Object.assign({}, op), { period: currentVotingPeriod === null || currentVotingPeriod === void 0 ? void 0 : currentVotingPeriod.voting_period.index }); case rpc_1.OpKind.PROPOSALS: if (currentVotingPeriod === undefined) { throw new error_1.RPCResponseError(`Failed to get the current voting period index`); } return Object.assign(Object.assign({}, op), { period: currentVotingPeriod === null || currentVotingPeriod === void 0 ? void 0 : currentVotingPeriod.voting_period.index }); default: throw new core_1.InvalidOperationKindError(JSON.stringify(op.kind)); } }); const contents = constructOps(ops); return { opOb: { branch: hash, contents, protocol, }, counter, }; }); } forge({ opOb: { branch, contents, protocol }, counter }) { return __awaiter(this, void 0, void 0, function* () { const forgedBytes = yield this.context.forger.forge({ branch, contents }); return { opbytes: forgedBytes, opOb: { branch, contents, protocol, }, counter, }; }); } simulate(op) { return __awaiter(this, void 0, void 0, function* () { return { opResponse: yield this.rpc.runOperation(op), op, context: this.context.clone(), }; }); } estimate(_a, estimator) { var { fee, gasLimit, storageLimit } = _a, rest = __rest(_a, ["fee", "gasLimit", "storageLimit"]); return __awaiter(this, void 0, void 0, function* () { let calculatedFee = fee; let calculatedGas = gasLimit; let calculatedStorage = storageLimit; if (calculatedFee && calculatedFee % 1 !== 0) { throw new operation_errors_1.InvalidEstimateValueError(`Fee value must not be a decimal: ${calculatedFee}`); } if (calculatedGas && calculatedGas % 1 !== 0) { throw new operation_errors_1.InvalidEstimateValueError(`Gas Limit value must not be a decimal: ${calculatedGas}`); } if (calculatedStorage && calculatedStorage % 1 !== 0) { throw new operation_errors_1.InvalidEstimateValueError(`Storage Limit value must not be a decimal: ${calculatedStorage}`); } if (fee === undefined || gasLimit === undefined || storageLimit === undefined) { const estimation = yield estimator(Object.assign({ fee, gasLimit, storageLimit }, rest)); if (calculatedFee === undefined) { calculatedFee = estimation.suggestedFeeMutez; } if (calculatedGas === undefined) { calculatedGas = estimation.gasLimit; } if (calculatedStorage === undefined) { calculatedStorage = estimation.storageLimit; } } return { fee: calculatedFee, gasLimit: calculatedGas, storageLimit: calculatedStorage, }; }); } signAndInject(forgedBytes) { return __awaiter(this, void 0, void 0, function* () { const signed = yield this.signer.sign(forgedBytes.opbytes, new Uint8Array([3])); forgedBytes.opbytes = signed.sbytes; forgedBytes.opOb.signature = signed.prefixSig; const opResponse = []; const results = yield this.rpc.preapplyOperations([forgedBytes.opOb]); if (!Array.isArray(results)) { throw new operation_errors_1.TezosPreapplyFailureError(results); } for (let i = 0; i < results.length; i++) { for (let j = 0; j < results[i].contents.length; j++) { opResponse.push(results[i].contents[j]); } } const errors = operation_errors_1.flattenErrors(results); if (errors.length) { throw new operation_errors_1.TezosOperationError(errors, 'Error occurred during validation simulation of operation'); } return { hash: yield this.context.injector.inject(forgedBytes.opbytes), forgedBytes, opResponse, context: this.context.clone(), }; }); } } exports.OperationEmitter = OperationEmitter; //# sourceMappingURL=operation-emitter.js.map