@taquito/taquito
Version:
High level functionality that builds upon the other packages in the Tezos Typescript Library Suite.
956 lines (929 loc) • 231 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@taquito/rpc'), require('rxjs'), require('rxjs/operators'), require('bignumber.js'), require('@taquito/michelson-encoder'), require('@taquito/utils'), require('@taquito/http-utils'), require('@taquito/michel-codec')) :
typeof define === 'function' && define.amd ? define(['exports', '@taquito/rpc', 'rxjs', 'rxjs/operators', 'bignumber.js', '@taquito/michelson-encoder', '@taquito/utils', '@taquito/http-utils', '@taquito/michel-codec'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.taquito = {}, global.rpc, global.rxjs, global.operators, global.BigNumber, global.michelsonEncoder, global.utils, global.httpUtils, global.michelCodec));
}(this, (function (exports, rpc, rxjs, operators, BigNumber, michelsonEncoder, utils, httpUtils, michelCodec) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var BigNumber__default = /*#__PURE__*/_interopDefaultLegacy(BigNumber);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(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;
}
function __awaiter(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());
});
}
function __generator(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 };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
var RpcForger = /** @class */ (function () {
function RpcForger(context) {
this.context = context;
}
RpcForger.prototype.forge = function (_a) {
var branch = _a.branch, contents = _a.contents;
return this.context.rpc.forgeOperations({ branch: branch, contents: contents });
};
return RpcForger;
}());
var RpcInjector = /** @class */ (function () {
function RpcInjector(context) {
this.context = context;
}
RpcInjector.prototype.inject = function (signedOperationBytes) {
return this.context.rpc.injectOperation(signedOperationBytes);
};
return RpcInjector;
}());
var UnconfiguredSignerError = /** @class */ (function () {
function UnconfiguredSignerError() {
this.name = 'UnconfiguredSignerError';
this.message = 'No signer has been configured. Please configure one by calling setProvider({signer}) on your TezosToolkit instance.';
}
return UnconfiguredSignerError;
}());
/**
* @description Default signer implementation which does nothing and produce invalid signature
*/
var NoopSigner = /** @class */ (function () {
function NoopSigner() {
}
NoopSigner.prototype.publicKey = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new UnconfiguredSignerError();
});
});
};
NoopSigner.prototype.publicKeyHash = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new UnconfiguredSignerError();
});
});
};
NoopSigner.prototype.secretKey = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new UnconfiguredSignerError();
});
});
};
NoopSigner.prototype.sign = function (_bytes, _watermark) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
throw new UnconfiguredSignerError();
});
});
};
return NoopSigner;
}());
var attachKind = function (op, kind) {
return __assign(__assign({}, op), { kind: kind });
};
var findWithKind = function (arr, kind) {
if (Array.isArray(arr)) {
var found = arr.find(function (op) { return op.kind === kind; });
if (found && isKind(found, kind)) {
return found;
}
}
};
var isKind = function (op, kind) {
return op.kind === kind;
};
var isOpWithFee = function (op) {
return ['transaction', 'delegation', 'origination', 'reveal'].indexOf(op.kind) !== -1;
};
var isOpRequireReveal = function (op) {
return ['transaction', 'delegation', 'origination'].indexOf(op.kind) !== -1;
};
var hasMetadata = function (op) {
return 'metadata' in op;
};
var hasMetadataWithResult = function (op) {
return hasMetadata(op) && 'operation_result' in op.metadata;
};
var hasMetadataWithInternalOperationResult = function (op) {
return hasMetadata(op) && 'internal_operation_results' in op.metadata;
};
var isErrorWithMessage = function (error) {
return 'with' in error;
};
var TezosOperationError = /** @class */ (function () {
function TezosOperationError(errors) {
this.errors = errors;
this.name = 'TezosOperationError';
// Last error is 'often' the one with more detail
var lastError = errors[errors.length - 1];
this.id = lastError.id;
this.kind = lastError.kind;
this.message = "(" + this.kind + ") " + this.id;
if (isErrorWithMessage(lastError) && lastError.with.string) {
this.message = lastError.with.string;
}
}
return TezosOperationError;
}());
var TezosPreapplyFailureError = /** @class */ (function () {
function TezosPreapplyFailureError(result) {
this.result = result;
this.name = 'TezosPreapplyFailureError';
this.message = 'Preapply returned an unexpected result';
}
return TezosPreapplyFailureError;
}());
// Flatten all operation content results and internal operation results into a single array
// Some cases where we can have multiple operation results or internal operation results are:
// - When an operation includes a reveal operation
// - When an operation is made using the batch API
// - Smart contract call can contains internal operation results when they call other smart contract internally or originate contracts
var flattenOperationResult = function (response) {
var results = Array.isArray(response) ? response : [response];
var returnedResults = [];
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].contents.length; j++) {
var content = results[i].contents[j];
if (hasMetadataWithResult(content)) {
returnedResults.push(__assign({ fee: content.fee }, content.metadata.operation_result));
if (Array.isArray(content.metadata.internal_operation_results)) {
content.metadata.internal_operation_results.forEach(function (x) { return returnedResults.push(x.result); });
}
}
}
}
return returnedResults;
};
/***
* @description Flatten all error from preapply response (including internal error)
*/
var flattenErrors = function (response, status) {
var e_1, _a;
if (status === void 0) { status = 'failed'; }
var results = Array.isArray(response) ? response : [response];
var errors = [];
// Transaction that do not fail will be backtracked in case one failure occur
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].contents.length; j++) {
var content = results[i].contents[j];
if (hasMetadata(content)) {
if (hasMetadataWithResult(content) && content.metadata.operation_result.status === status) {
errors = errors.concat(content.metadata.operation_result.errors || []);
}
if (hasMetadataWithInternalOperationResult(content) &&
Array.isArray(content.metadata.internal_operation_results)) {
try {
for (var _b = (e_1 = void 0, __values(content.metadata.internal_operation_results)), _c = _b.next(); !_c.done; _c = _b.next()) {
var internalResult = _c.value;
if ('result' in internalResult && internalResult.result.status === status) {
errors = errors.concat(internalResult.result.errors || []);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
}
}
}
return errors;
};
var receiptFromOperation = function (op, _a) {
var _b = _a === void 0 ? {
ALLOCATION_BURN: 257,
ORIGINATION_BURN: 257,
} : _a, ALLOCATION_BURN = _b.ALLOCATION_BURN, ORIGINATION_BURN = _b.ORIGINATION_BURN;
var operationResults = flattenOperationResult({ contents: op });
var totalGas = new BigNumber__default['default'](0);
var totalStorage = new BigNumber__default['default'](0);
var totalFee = new BigNumber__default['default'](0);
var totalOriginationBurn = new BigNumber__default['default'](0);
var totalAllocationBurn = new BigNumber__default['default'](0);
var totalPaidStorageDiff = new BigNumber__default['default'](0);
operationResults.forEach(function (result) {
totalFee = totalFee.plus(result.fee || 0);
totalOriginationBurn = totalOriginationBurn.plus(Array.isArray(result.originated_contracts)
? result.originated_contracts.length * ORIGINATION_BURN
: 0);
totalAllocationBurn = totalAllocationBurn.plus('allocated_destination_contract' in result ? ALLOCATION_BURN : 0);
totalGas = totalGas.plus(result.consumed_gas || 0);
totalPaidStorageDiff = totalPaidStorageDiff.plus('paid_storage_size_diff' in result ? Number(result.paid_storage_size_diff) || 0 : 0);
});
totalStorage = totalStorage
.plus(totalAllocationBurn)
.plus(totalOriginationBurn)
.plus(totalPaidStorageDiff);
return {
totalFee: totalFee,
totalGas: totalGas,
totalStorage: totalStorage,
totalAllocationBurn: totalAllocationBurn,
totalOriginationBurn: totalOriginationBurn,
totalPaidStorageDiff: totalPaidStorageDiff,
totalStorageBurn: new BigNumber__default['default'](totalStorage.multipliedBy(1000)),
};
};
var MissedBlockDuringConfirmationError = /** @class */ (function () {
function MissedBlockDuringConfirmationError() {
this.name = 'MissedBlockDuringConfirmationError';
this.message = 'Taquito missed a block while waiting for operation confirmation and was not able to find the operation';
}
return MissedBlockDuringConfirmationError;
}());
var MAX_BRANCH_ANCESTORS = 60;
/**
* @description WalletOperation allows to monitor operation inclusion on chains and surface information related to the operation
*/
var WalletOperation = /** @class */ (function () {
/**
*
* @param opHash Operation hash
* @param raw Raw operation that was injected
* @param context Taquito context allowing access to rpc and signer
*/
function WalletOperation(opHash, context, _newHead$) {
var _this = this;
this.opHash = opHash;
this.context = context;
this._newHead$ = _newHead$;
this._operationResult = new rxjs.ReplaySubject(1);
this._includedInBlock = new rxjs.ReplaySubject(1);
this._included = false;
this.newHead$ = this._newHead$.pipe(operators.tap(function (newHead) {
if (!_this._included &&
_this.lastHead &&
newHead.header.level - _this.lastHead.header.level > 1) {
throw new MissedBlockDuringConfirmationError();
}
_this.lastHead = newHead;
}), operators.shareReplay({ bufferSize: 1, refCount: true }));
// Observable that emit once operation is seen in a block
this.confirmed$ = this.newHead$.pipe(operators.map(function (head) {
var e_1, _a, e_2, _b;
try {
for (var _c = __values(head.operations), _d = _c.next(); !_d.done; _d = _c.next()) {
var opGroup = _d.value;
try {
for (var opGroup_1 = (e_2 = void 0, __values(opGroup)), opGroup_1_1 = opGroup_1.next(); !opGroup_1_1.done; opGroup_1_1 = opGroup_1.next()) {
var op = opGroup_1_1.value;
if (op.hash === _this.opHash) {
_this._included = true;
_this._includedInBlock.next(head);
_this._operationResult.next(op.contents);
// Return the block where the operation was found
return head;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (opGroup_1_1 && !opGroup_1_1.done && (_b = opGroup_1.return)) _b.call(opGroup_1);
}
finally { if (e_2) throw e_2.error; }
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
}), operators.filter(function (x) {
return typeof x !== 'undefined';
}), operators.first(), operators.shareReplay({ bufferSize: 1, refCount: true }));
this.confirmed$.pipe(operators.first()).subscribe();
}
WalletOperation.prototype.operationResults = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._operationResult.pipe(operators.first()).toPromise()];
});
});
};
/**
* @description Receipt expose the total amount of tezos token burn and spent on fees
* The promise returned by receipt will resolve only once the transaction is included
*/
WalletOperation.prototype.receipt = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = receiptFromOperation;
return [4 /*yield*/, this.operationResults()];
case 1: return [2 /*return*/, _a.apply(void 0, [_b.sent()])];
}
});
});
};
WalletOperation.prototype.getCurrentConfirmation = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (!this._included) {
return [2 /*return*/, 0];
}
return [2 /*return*/, rxjs.combineLatest([this._includedInBlock, rxjs.from(this.context.rpc.getBlock())])
.pipe(operators.map(function (_a) {
var _b = __read(_a, 2), foundAtBlock = _b[0], head = _b[1];
return head.header.level - foundAtBlock.header.level + 1;
}), operators.first())
.toPromise()];
});
});
};
WalletOperation.prototype.isInCurrentBranch = function (tipBlockIdentifier) {
if (tipBlockIdentifier === void 0) { tipBlockIdentifier = 'head'; }
return __awaiter(this, void 0, void 0, function () {
var tipBlockHeader, inclusionBlock, levelDiff, tipBlockLevel, blocks, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// By default it is assumed that the operation is in the current branch
if (!this._included) {
return [2 /*return*/, true];
}
return [4 /*yield*/, this.context.rpc.getBlockHeader({ block: tipBlockIdentifier })];
case 1:
tipBlockHeader = _b.sent();
return [4 /*yield*/, this._includedInBlock.pipe(operators.first()).toPromise()];
case 2:
inclusionBlock = _b.sent();
levelDiff = tipBlockHeader.level - inclusionBlock.header.level;
// Block produced before the operation is included are assumed to be part of the current branch
if (levelDiff <= 0) {
return [2 /*return*/, true];
}
tipBlockLevel = Math.min(inclusionBlock.header.level + levelDiff, inclusionBlock.header.level + MAX_BRANCH_ANCESTORS);
_a = Set.bind;
return [4 /*yield*/, this.context.rpc.getLiveBlocks({ block: String(tipBlockLevel) })];
case 3:
blocks = new (_a.apply(Set, [void 0, _b.sent()]))();
return [2 /*return*/, blocks.has(inclusionBlock.hash)];
}
});
});
};
WalletOperation.prototype.confirmationObservable = function (confirmations) {
var _this = this;
if (typeof confirmations !== 'undefined' && confirmations < 1) {
throw new Error('Confirmation count must be at least 1');
}
var defaultConfirmationCount = this.context.config.defaultConfirmationCount;
var conf = confirmations !== undefined ? confirmations : defaultConfirmationCount;
return rxjs.combineLatest([this._includedInBlock, this.newHead$]).pipe(operators.distinctUntilChanged(function (_a, _b) {
var _c = __read(_a, 2), previousHead = _c[1];
var _d = __read(_b, 2), newHead = _d[1];
return previousHead.hash === newHead.hash;
}), operators.map(function (_a) {
var _b = __read(_a, 2), foundAtBlock = _b[0], head = _b[1];
return {
block: head,
expectedConfirmation: conf,
currentConfirmation: head.header.level - foundAtBlock.header.level + 1,
completed: head.header.level - foundAtBlock.header.level >= conf - 1,
isInCurrentBranch: function () { return _this.isInCurrentBranch(head.hash); },
};
}), operators.takeWhile(function (_a) {
var completed = _a.completed;
return !completed;
}, true));
};
/**
*
* @param confirmations [0] Number of confirmation to wait for
*/
WalletOperation.prototype.confirmation = function (confirmations) {
return this.confirmationObservable(confirmations).toPromise();
};
return WalletOperation;
}());
var DelegationWalletOperation = /** @class */ (function (_super) {
__extends(DelegationWalletOperation, _super);
function DelegationWalletOperation(opHash, context, newHead$) {
var _this = _super.call(this, opHash, context, newHead$) || this;
_this.opHash = opHash;
_this.context = context;
return _this;
}
DelegationWalletOperation.prototype.revealOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, operationResult.find(function (x) { return x.kind === rpc.OpKind.REVEAL; })];
}
});
});
};
DelegationWalletOperation.prototype.delegationOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, operationResult.find(function (x) { return x.kind === rpc.OpKind.DELEGATION; })];
}
});
});
};
DelegationWalletOperation.prototype.status = function () {
return __awaiter(this, void 0, void 0, function () {
var op;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this._included) {
return [2 /*return*/, 'pending'];
}
return [4 /*yield*/, this.delegationOperation()];
case 1:
op = _a.sent();
if (!op) {
return [2 /*return*/, 'unknown'];
}
return [2 /*return*/, op.metadata.operation_result.status];
}
});
});
};
return DelegationWalletOperation;
}(WalletOperation));
var OriginationWalletOperation = /** @class */ (function (_super) {
__extends(OriginationWalletOperation, _super);
function OriginationWalletOperation(opHash, context, newHead$) {
var _this = _super.call(this, opHash, context, newHead$) || this;
_this.opHash = opHash;
_this.context = context;
return _this;
}
OriginationWalletOperation.prototype.originationOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, findWithKind(operationResult, rpc.OpKind.ORIGINATION)];
}
});
});
};
OriginationWalletOperation.prototype.revealOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, findWithKind(operationResult, rpc.OpKind.REVEAL)];
}
});
});
};
OriginationWalletOperation.prototype.status = function () {
return __awaiter(this, void 0, void 0, function () {
var op;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this._included) {
return [2 /*return*/, 'pending'];
}
return [4 /*yield*/, this.originationOperation()];
case 1:
op = _a.sent();
if (!op) {
return [2 /*return*/, 'unknown'];
}
return [2 /*return*/, op.metadata.operation_result.status];
}
});
});
};
OriginationWalletOperation.prototype.contract = function () {
return __awaiter(this, void 0, void 0, function () {
var op, address;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.originationOperation()];
case 1:
op = _a.sent();
address = (op.metadata.operation_result.originated_contracts || [])[0];
return [2 /*return*/, this.context.wallet.at(address)];
}
});
});
};
return OriginationWalletOperation;
}(WalletOperation));
var TransactionWalletOperation = /** @class */ (function (_super) {
__extends(TransactionWalletOperation, _super);
function TransactionWalletOperation(opHash, context, newHead$) {
var _this = _super.call(this, opHash, context, newHead$) || this;
_this.opHash = opHash;
_this.context = context;
return _this;
}
TransactionWalletOperation.prototype.revealOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, operationResult.find(function (x) { return x.kind === rpc.OpKind.REVEAL; })];
}
});
});
};
TransactionWalletOperation.prototype.transactionOperation = function () {
return __awaiter(this, void 0, void 0, function () {
var operationResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.operationResults()];
case 1:
operationResult = _a.sent();
return [2 /*return*/, operationResult.find(function (x) { return x.kind === rpc.OpKind.TRANSACTION; })];
}
});
});
};
TransactionWalletOperation.prototype.status = function () {
return __awaiter(this, void 0, void 0, function () {
var op;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this._included) {
return [2 /*return*/, 'pending'];
}
return [4 /*yield*/, this.transactionOperation()];
case 1:
op = _a.sent();
if (!op) {
return [2 /*return*/, 'unknown'];
}
return [2 /*return*/, op.metadata.operation_result.status];
}
});
});
};
return TransactionWalletOperation;
}(WalletOperation));
var cacheUntil = function (cacheUntilObs) { return function (source) {
var subject = null;
return rxjs.defer(function () {
if (!subject) {
subject = new rxjs.ReplaySubject();
source.pipe(operators.first()).subscribe(subject);
cacheUntilObs.pipe(operators.first()).subscribe(function () {
subject = null;
});
}
return subject;
});
}; };
var createNewPollingBasedHeadObservable = function (pollingTimer, sharedHeadOb, context, scheduler) {
return pollingTimer.pipe(operators.switchMap(function () { return sharedHeadOb; }), operators.distinctUntilKeyChanged('hash'), operators.timeoutWith(context.config.confirmationPollingTimeoutSecond * 1000, rxjs.throwError(new Error('Confirmation polling timed out')), scheduler), operators.shareReplay({
refCount: true,
scheduler: scheduler,
}));
};
var OperationFactory = /** @class */ (function () {
function OperationFactory(context) {
var _this = this;
this.context = context;
// Cache the last block for one second across all operations
this.sharedHeadObs = rxjs.defer(function () { return rxjs.from(_this.context.rpc.getBlock()); }).pipe(cacheUntil(rxjs.timer(0, 1000)));
}
OperationFactory.prototype.createNewHeadObservable = function () {
return createNewPollingBasedHeadObservable(rxjs.timer(0, this.context.config.confirmationPollingIntervalSecond * 1000), this.sharedHeadObs, this.context);
};
OperationFactory.prototype.createPastBlockWalker = function (startBlock, count) {
var _this = this;
if (count === void 0) { count = 1; }
return rxjs.from(this.context.rpc.getBlock({ block: startBlock })).pipe(operators.switchMap(function (block) {
if (count === 1) {
return rxjs.of(block);
}
return rxjs.range(block.header.level, count - 1).pipe(operators.startWith(block), operators.concatMap(function (level) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.context.rpc.getBlock({ block: String(level) })];
});
}); }));
}));
};
OperationFactory.prototype.createHeadObservableFromConfig = function (_a) {
var blockIdentifier = _a.blockIdentifier;
var observableSequence = [];
if (blockIdentifier) {
observableSequence.push(this.createPastBlockWalker(blockIdentifier));
}
observableSequence.push(this.createNewHeadObservable());
return rxjs.concat.apply(void 0, __spread(observableSequence));
};
OperationFactory.prototype.createOperation = function (hash, config) {
if (config === void 0) { config = {}; }
return new WalletOperation(hash, this.context.clone(), this.createHeadObservableFromConfig(config));
};
OperationFactory.prototype.createTransactionOperation = function (hash, config) {
if (config === void 0) { config = {}; }
return new TransactionWalletOperation(hash, this.context.clone(), this.createHeadObservableFromConfig(config));
};
OperationFactory.prototype.createDelegationOperation = function (hash, config) {
if (config === void 0) { config = {}; }
return new DelegationWalletOperation(hash, this.context.clone(), this.createHeadObservableFromConfig(config));
};
OperationFactory.prototype.createOriginationOperation = function (hash, config) {
if (config === void 0) { config = {}; }
return new OriginationWalletOperation(hash, this.context.clone(), this.createHeadObservableFromConfig(config));
};
return OperationFactory;
}());
(function (DEFAULT_GAS_LIMIT) {
DEFAULT_GAS_LIMIT[DEFAULT_GAS_LIMIT["DELEGATION"] = 10600] = "DELEGATION";
DEFAULT_GAS_LIMIT[DEFAULT_GAS_LIMIT["ORIGINATION"] = 10600] = "ORIGINATION";
DEFAULT_GAS_LIMIT[DEFAULT_GAS_LIMIT["TRANSFER"] = 10600] = "TRANSFER";
DEFAULT_GAS_LIMIT[DEFAULT_GAS_LIMIT["REVEAL"] = 10600] = "REVEAL";
})(exports.DEFAULT_GAS_LIMIT || (exports.DEFAULT_GAS_LIMIT = {}));
(function (DEFAULT_FEE) {
DEFAULT_FEE[DEFAULT_FEE["DELEGATION"] = 1257] = "DELEGATION";
DEFAULT_FEE[DEFAULT_FEE["ORIGINATION"] = 10000] = "ORIGINATION";
DEFAULT_FEE[DEFAULT_FEE["TRANSFER"] = 10000] = "TRANSFER";
DEFAULT_FEE[DEFAULT_FEE["REVEAL"] = 1420] = "REVEAL";
})(exports.DEFAULT_FEE || (exports.DEFAULT_FEE = {}));
(function (DEFAULT_STORAGE_LIMIT) {
DEFAULT_STORAGE_LIMIT[DEFAULT_STORAGE_LIMIT["DELEGATION"] = 0] = "DELEGATION";
DEFAULT_STORAGE_LIMIT[DEFAULT_STORAGE_LIMIT["ORIGINATION"] = 257] = "ORIGINATION";
DEFAULT_STORAGE_LIMIT[DEFAULT_STORAGE_LIMIT["TRANSFER"] = 257] = "TRANSFER";
DEFAULT_STORAGE_LIMIT[DEFAULT_STORAGE_LIMIT["REVEAL"] = 0] = "REVEAL";
})(exports.DEFAULT_STORAGE_LIMIT || (exports.DEFAULT_STORAGE_LIMIT = {}));
(function (Protocols) {
Protocols["Pt24m4xi"] = "Pt24m4xiPbLDhVgVfABUjirbmda3yohdN82Sp9FeuAXJ4eV9otd";
Protocols["PsBABY5H"] = "PsBABY5HQTSkA4297zNHfsZNKtxULfL18y95qb3m53QJiXGmrbU";
Protocols["PsBabyM1"] = "PsBabyM1eUXZseaJdmXFApDSBqj8YBfwELoxZHHW77EMcAbbwAS";
Protocols["PsCARTHA"] = "PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb";
Protocols["PsDELPH1"] = "PsDELPH1Kxsxt8f9eWbxQeRxkjfbxoqM52jvs5Y5fBxWWh4ifpo";
Protocols["PtEdo27k"] = "PtEdo2ZkT9oKpimTah6x2embF25oss54njMuPzkJTEi5RqfdZFA";
})(exports.Protocols || (exports.Protocols = {}));
var protocols = {
'004': [exports.Protocols.Pt24m4xi],
'005': [exports.Protocols.PsBABY5H, exports.Protocols.PsBabyM1],
'006': [exports.Protocols.PsCARTHA],
'007': [exports.Protocols.PsDELPH1],
'008': [exports.Protocols.PtEdo27k] // edonet v2
};
(function (DefaultLambdaAddresses) {
DefaultLambdaAddresses["MAINNET"] = "KT1CPuTzwC7h7uLXd5WQmpMFso1HxrLBUtpE";
DefaultLambdaAddresses["CARTHAGENET"] = "KT1VAy1o1FGiXYfD3YT7x7k5eF5HSHhmc1u6";
DefaultLambdaAddresses["DELPHINET"] = "KT19abMFs3haqyKYwqdLjK9GbtofryZLvpiK";
DefaultLambdaAddresses["EDONET"] = "KT1A64nVZDccAHGAsf1ZyVajXZcbiwjV3SnN";
})(exports.DefaultLambdaAddresses || (exports.DefaultLambdaAddresses = {}));
(function (ChainIds) {
ChainIds["MAINNET"] = "NetXdQprcVkpaWU";
ChainIds["CARTHAGENET"] = "NetXjD3HPJJjmcd";
ChainIds["DELPHINET"] = "NetXm8tYqnMWky1";
ChainIds["EDONET"] = "NetXSgo1ZT2DRUG";
})(exports.ChainIds || (exports.ChainIds = {}));
var OperationEmitter = /** @class */ (function () {
function OperationEmitter(context) {
this.context = context;
}
Object.defineProperty(OperationEmitter.prototype, "rpc", {
get: function () {
return this.context.rpc;
},
enumerable: false,
configurable: true
});
Object.defineProperty(OperationEmitter.prototype, "signer", {
get: function () {
return this.context.signer;
},
enumerable: false,
configurable: true
});
// Originally from sotez (Copyright (c) 2018 Andrew Kishino)
OperationEmitter.prototype.prepareOperation = function (_a) {
var operation = _a.operation, source = _a.source;
return __awaiter(this, void 0, void 0, function () {
var counter, counters, requiresReveal, ops, head, blockHeaderPromise, blockMetaPromise, publicKeyHash, counterPromise, managerPromise, i, counter_1, _b, header, metadata, headCounter, manager, haveManager, reveal, getFee, getSource, constructOps, branch, contents, protocol;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
counters = {};
requiresReveal = false;
ops = [];
blockHeaderPromise = this.rpc.getBlockHeader();
blockMetaPromise = this.rpc.getBlockMetadata();
if (Array.isArray(operation)) {
ops = __spread(operation);
}
else {
ops = [operation];
}
return [4 /*yield*/, this.signer.publicKeyHash()];
case 1:
publicKeyHash = _d.sent();
counterPromise = Promise.resolve(undefined);
managerPromise = Promise.resolve(undefined);
i = 0;
_d.label = 2;
case 2:
if (!(i < ops.length)) return [3 /*break*/, 5];
if (!isOpRequireReveal(ops[i])) return [3 /*break*/, 4];
requiresReveal = true;
return [4 /*yield*/, this.rpc.getContract(publicKeyHash)];
case 3:
counter_1 = (_d.sent()).counter;
counterPromise = Promise.resolve(counter_1);
managerPromise = this.rpc.getManagerKey(publicKeyHash);
return [3 /*break*/, 5];
case 4:
i++;
return [3 /*break*/, 2];
case 5: return [4 /*yield*/, Promise.all([
blockHeaderPromise,
blockMetaPromise,
counterPromise,
managerPromise,
])];
case 6:
_b = __read.apply(void 0, [_d.sent(), 4]), header = _b[0], metadata = _b[1], headCounter = _b[2], manager = _b[3];
if (!header) {
throw new Error('Unable to fetch latest block header');
}
if (!metadata) {
throw new Error('Unable to fetch latest metadata');
}
head = header;
if (!requiresReveal) return [3 /*break*/, 8];
haveManager = manager && typeof manager === 'object' ? !!manager.key : !!manager;
if (!!haveManager) return [3 /*break*/, 8];
_c = {
kind: rpc.OpKind.REVEAL,
fee: exports.DEFAULT_FEE.REVEAL
};
return [4 /*yield*/, this.signer.publicKey()];
case 7:
reveal = (_c.public_key = _d.sent(),
_c.source = publicKeyHash,
_c.gas_limit = exports.DEFAULT_GAS_LIMIT.REVEAL,
_c.storage_limit = exports.DEFAULT_STORAGE_LIMIT.REVEAL,
_c);
ops.unshift(reveal);
_d.label = 8;
case 8:
counter = parseInt(headCounter || '0', 10);
if (!counters[publicKeyHash] || counters[publicKeyHash] < counter) {
counters[publicKeyHash] = counter;
}
getFee = function (op) {
var opCounter = ++counters[publicKeyHash];
return {
counter: "" + opCounter,
// tslint:disable-next-line: strict-type-predicates
fee: typeof op.fee === 'undefined' ? '0' : "" + op.fee,
// tslint:disable-next-line: strict-type-predicates
gas_limit: typeof op.gas_limit === 'undefined' ? '0' : "" + op.gas_limit,
// tslint:disable-next-line: strict-type-predicates
storage_limit: typeof op.storage_limit === 'undefined' ? '0' : "" + op.storage_limit,
};
};
getSource = function (op) {
return {
source: typeof op.source === 'undefined' ? source || publicKeyHash : op.source,
};
};
constructOps = function (cOps) {
// tslint:disable strict-type-predicates
return cOps.map(function (op) {
switch (op.kind) {
case rpc.OpKind.ACTIVATION:
return __assign({}, op);
case rpc.OpKind.REVEAL:
return __assign(__assign(__assign({}, op), getSource(op)), getFee(op));
case rpc.OpKind.ORIGINATION:
return __assign(__assign(__assign(__assign({}, op), { balance: typeof op.balance !== 'undefined' ? "" + op.balance : '0' }), getSource(op)), getFee(op));
case rpc.OpKind.TRANSA