UNPKG

45.5 kBJavaScriptView Raw
1"use strict";
2/**
3 * @module API
4 */
5// copyright defined in eosjs/LICENSE.txt
6/* eslint-disable max-classes-per-file */
7var __assign = (this && this.__assign) || function () {
8 __assign = Object.assign || function(t) {
9 for (var s, i = 1, n = arguments.length; i < n; i++) {
10 s = arguments[i];
11 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12 t[p] = s[p];
13 }
14 return t;
15 };
16 return __assign.apply(this, arguments);
17};
18var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20 return new (P || (P = Promise))(function (resolve, reject) {
21 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24 step((generator = generator.apply(thisArg, _arguments || [])).next());
25 });
26};
27var __generator = (this && this.__generator) || function (thisArg, body) {
28 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30 function verb(n) { return function (v) { return step([n, v]); }; }
31 function step(op) {
32 if (f) throw new TypeError("Generator is already executing.");
33 while (_) try {
34 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;
35 if (y = 0, t) op = [op[0] & 2, t.value];
36 switch (op[0]) {
37 case 0: case 1: t = op; break;
38 case 4: _.label++; return { value: op[1], done: false };
39 case 5: _.label++; y = op[1]; op = [0]; continue;
40 case 7: op = _.ops.pop(); _.trys.pop(); continue;
41 default:
42 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46 if (t[2]) _.ops.pop();
47 _.trys.pop(); continue;
48 }
49 op = body.call(thisArg, _);
50 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52 }
53};
54var __read = (this && this.__read) || function (o, n) {
55 var m = typeof Symbol === "function" && o[Symbol.iterator];
56 if (!m) return o;
57 var i = m.call(o), r, ar = [], e;
58 try {
59 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
60 }
61 catch (error) { e = { error: error }; }
62 finally {
63 try {
64 if (r && !r.done && (m = i["return"])) m.call(i);
65 }
66 finally { if (e) throw e.error; }
67 }
68 return ar;
69};
70var __spreadArray = (this && this.__spreadArray) || function (to, from) {
71 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
72 to[j] = from[i];
73 return to;
74};
75var __values = (this && this.__values) || function(o) {
76 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
77 if (m) return m.call(o);
78 if (o && typeof o.length === "number") return {
79 next: function () {
80 if (o && i >= o.length) o = void 0;
81 return { value: o && o[i++], done: !o };
82 }
83 };
84 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
85};
86Object.defineProperty(exports, "__esModule", { value: true });
87exports.ActionBuilder = exports.TransactionBuilder = exports.Api = void 0;
88var pako_1 = require("pako");
89var ser = require("./eosjs-serialize");
90var Api = /** @class */ (function () {
91 /**
92 * @param args
93 * * `rpc`: Issues RPC calls
94 * * `authorityProvider`: Get public keys needed to meet authorities in a transaction
95 * * `abiProvider`: Supplies ABIs in raw form (binary)
96 * * `signatureProvider`: Signs transactions
97 * * `chainId`: Identifies chain
98 * * `textEncoder`: `TextEncoder` instance to use. Pass in `null` if running in a browser
99 * * `textDecoder`: `TextDecoder` instance to use. Pass in `null` if running in a browser
100 */
101 function Api(args) {
102 /** Holds information needed to serialize contract actions */
103 this.contracts = new Map();
104 /** Fetched abis */
105 this.cachedAbis = new Map();
106 this.transactionExtensions = [
107 { id: 1, type: 'resource_payer', keys: ['payer', 'max_net_bytes', 'max_cpu_us', 'max_memory_bytes'] },
108 ];
109 this.rpc = args.rpc;
110 this.authorityProvider = args.authorityProvider || args.rpc;
111 this.abiProvider = args.abiProvider || args.rpc;
112 this.signatureProvider = args.signatureProvider;
113 this.chainId = args.chainId;
114 this.textEncoder = args.textEncoder;
115 this.textDecoder = args.textDecoder;
116 this.abiTypes = ser.getTypesFromAbi(ser.createAbiTypes());
117 this.transactionTypes = ser.getTypesFromAbi(ser.createTransactionTypes());
118 }
119 /** Decodes an abi as Uint8Array into json. */
120 Api.prototype.rawAbiToJson = function (rawAbi) {
121 var buffer = new ser.SerialBuffer({
122 textEncoder: this.textEncoder,
123 textDecoder: this.textDecoder,
124 array: rawAbi,
125 });
126 if (!ser.supportedAbiVersion(buffer.getString())) {
127 throw new Error('Unsupported abi version');
128 }
129 buffer.restartRead();
130 return this.abiTypes.get('abi_def').deserialize(buffer);
131 };
132 /** Encodes a json abi as Uint8Array. */
133 Api.prototype.jsonToRawAbi = function (jsonAbi) {
134 var buffer = new ser.SerialBuffer({
135 textEncoder: this.textEncoder,
136 textDecoder: this.textDecoder,
137 });
138 this.abiTypes.get('abi_def').serialize(buffer, jsonAbi);
139 if (!ser.supportedAbiVersion(buffer.getString())) {
140 throw new Error('Unsupported abi version');
141 }
142 return buffer.asUint8Array();
143 };
144 /** Get abi in both binary and structured forms. Fetch when needed. */
145 Api.prototype.getCachedAbi = function (accountName, reload) {
146 if (reload === void 0) { reload = false; }
147 return __awaiter(this, void 0, void 0, function () {
148 var cachedAbi, rawAbi, abi, e_1;
149 return __generator(this, function (_a) {
150 switch (_a.label) {
151 case 0:
152 if (!reload && this.cachedAbis.get(accountName)) {
153 return [2 /*return*/, this.cachedAbis.get(accountName)];
154 }
155 _a.label = 1;
156 case 1:
157 _a.trys.push([1, 3, , 4]);
158 return [4 /*yield*/, this.abiProvider.getRawAbi(accountName)];
159 case 2:
160 rawAbi = (_a.sent()).abi;
161 abi = this.rawAbiToJson(rawAbi);
162 cachedAbi = { rawAbi: rawAbi, abi: abi };
163 return [3 /*break*/, 4];
164 case 3:
165 e_1 = _a.sent();
166 e_1.message = "fetching abi for " + accountName + ": " + e_1.message;
167 throw e_1;
168 case 4:
169 if (!cachedAbi) {
170 throw new Error("Missing abi for " + accountName);
171 }
172 this.cachedAbis.set(accountName, cachedAbi);
173 return [2 /*return*/, cachedAbi];
174 }
175 });
176 });
177 };
178 /** Get abi in structured form. Fetch when needed. */
179 Api.prototype.getAbi = function (accountName, reload) {
180 if (reload === void 0) { reload = false; }
181 return __awaiter(this, void 0, void 0, function () {
182 return __generator(this, function (_a) {
183 switch (_a.label) {
184 case 0: return [4 /*yield*/, this.getCachedAbi(accountName, reload)];
185 case 1: return [2 /*return*/, (_a.sent()).abi];
186 }
187 });
188 });
189 };
190 /** Get abis needed by a transaction */
191 Api.prototype.getTransactionAbis = function (transaction, reload) {
192 if (reload === void 0) { reload = false; }
193 return __awaiter(this, void 0, void 0, function () {
194 var actions, accounts, uniqueAccounts, actionPromises;
195 var _this = this;
196 return __generator(this, function (_a) {
197 actions = (transaction.context_free_actions || []).concat(transaction.actions);
198 accounts = actions.map(function (action) { return action.account; });
199 uniqueAccounts = new Set(accounts);
200 actionPromises = __spreadArray([], __read(uniqueAccounts)).map(function (account) { return __awaiter(_this, void 0, void 0, function () {
201 var _a;
202 return __generator(this, function (_b) {
203 switch (_b.label) {
204 case 0:
205 _a = {
206 accountName: account
207 };
208 return [4 /*yield*/, this.getCachedAbi(account, reload)];
209 case 1: return [2 /*return*/, (_a.abi = (_b.sent()).rawAbi,
210 _a)];
211 }
212 });
213 }); });
214 return [2 /*return*/, Promise.all(actionPromises)];
215 });
216 });
217 };
218 /** Get data needed to serialize actions in a contract */
219 Api.prototype.getContract = function (accountName, reload) {
220 if (reload === void 0) { reload = false; }
221 return __awaiter(this, void 0, void 0, function () {
222 var abi, types, actions, _a, _b, _c, name_1, type, result;
223 var e_2, _d;
224 return __generator(this, function (_e) {
225 switch (_e.label) {
226 case 0:
227 if (!reload && this.contracts.get(accountName)) {
228 return [2 /*return*/, this.contracts.get(accountName)];
229 }
230 return [4 /*yield*/, this.getAbi(accountName, reload)];
231 case 1:
232 abi = _e.sent();
233 types = ser.getTypesFromAbi(ser.createInitialTypes(), abi);
234 actions = new Map();
235 try {
236 for (_a = __values(abi.actions), _b = _a.next(); !_b.done; _b = _a.next()) {
237 _c = _b.value, name_1 = _c.name, type = _c.type;
238 actions.set(name_1, ser.getType(types, type));
239 }
240 }
241 catch (e_2_1) { e_2 = { error: e_2_1 }; }
242 finally {
243 try {
244 if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
245 }
246 finally { if (e_2) throw e_2.error; }
247 }
248 result = { types: types, actions: actions };
249 this.contracts.set(accountName, result);
250 return [2 /*return*/, result];
251 }
252 });
253 });
254 };
255 /** Convert `value` to binary form. `type` must be a built-in abi type or in `transaction.abi.json`. */
256 Api.prototype.serialize = function (buffer, type, value) {
257 this.transactionTypes.get(type).serialize(buffer, value);
258 };
259 /** Convert data in `buffer` to structured form. `type` must be a built-in abi type or in `transaction.abi.json`. */
260 Api.prototype.deserialize = function (buffer, type) {
261 return this.transactionTypes.get(type).deserialize(buffer);
262 };
263 /** Convert a transaction to binary */
264 Api.prototype.serializeTransaction = function (transaction) {
265 var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
266 this.serialize(buffer, 'transaction', __assign({ max_net_usage_words: 0, max_cpu_usage_ms: 0, delay_sec: 0, context_free_actions: [], actions: [], transaction_extensions: [] }, transaction));
267 return buffer.asUint8Array();
268 };
269 /** Serialize context-free data */
270 Api.prototype.serializeContextFreeData = function (contextFreeData) {
271 var e_3, _a;
272 if (!contextFreeData || !contextFreeData.length) {
273 return null;
274 }
275 var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
276 buffer.pushVaruint32(contextFreeData.length);
277 try {
278 for (var contextFreeData_1 = __values(contextFreeData), contextFreeData_1_1 = contextFreeData_1.next(); !contextFreeData_1_1.done; contextFreeData_1_1 = contextFreeData_1.next()) {
279 var data = contextFreeData_1_1.value;
280 buffer.pushBytes(data);
281 }
282 }
283 catch (e_3_1) { e_3 = { error: e_3_1 }; }
284 finally {
285 try {
286 if (contextFreeData_1_1 && !contextFreeData_1_1.done && (_a = contextFreeData_1.return)) _a.call(contextFreeData_1);
287 }
288 finally { if (e_3) throw e_3.error; }
289 }
290 return buffer.asUint8Array();
291 };
292 /** Convert a transaction from binary. Leaves actions in hex. */
293 Api.prototype.deserializeTransaction = function (transaction) {
294 var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
295 buffer.pushArray(transaction);
296 return this.deserialize(buffer, 'transaction');
297 };
298 // Order of adding to transaction_extension is transaction_extension id ascending
299 Api.prototype.serializeTransactionExtensions = function (transaction) {
300 var transaction_extensions = [];
301 if (transaction.resource_payer) {
302 var extensionBuffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
303 var types = ser.getTypesFromAbi(ser.createTransactionExtensionTypes());
304 types.get('resource_payer').serialize(extensionBuffer, transaction.resource_payer);
305 transaction_extensions = __spreadArray(__spreadArray([], __read(transaction_extensions)), [[1, ser.arrayToHex(extensionBuffer.asUint8Array())]]);
306 }
307 return transaction_extensions;
308 };
309 ;
310 // Usage: transaction = {...transaction, ...this.deserializeTransactionExtensions(transaction.transaction_extensions)}
311 Api.prototype.deserializeTransactionExtensions = function (data) {
312 var _this = this;
313 var transaction = {};
314 data.forEach(function (extensionData) {
315 var transactionExtension = _this.transactionExtensions.find(function (extension) { return extension.id === extensionData[0]; });
316 if (transactionExtension === undefined) {
317 throw new Error("Transaction Extension could not be determined: " + extensionData);
318 }
319 var types = ser.getTypesFromAbi(ser.createTransactionExtensionTypes());
320 var extensionBuffer = new ser.SerialBuffer({ textEncoder: _this.textEncoder, textDecoder: _this.textDecoder });
321 extensionBuffer.pushArray(ser.hexToUint8Array(extensionData[1]));
322 var deserializedObj = types.get(transactionExtension.type).deserialize(extensionBuffer);
323 if (extensionData[0] === 1) {
324 deserializedObj.max_net_bytes = Number(deserializedObj.max_net_bytes);
325 deserializedObj.max_cpu_us = Number(deserializedObj.max_cpu_us);
326 deserializedObj.max_memory_bytes = Number(deserializedObj.max_memory_bytes);
327 transaction.resource_payer = deserializedObj;
328 }
329 });
330 return transaction;
331 };
332 ;
333 // Transaction extensions are serialized and moved to `transaction_extensions`, deserialized objects are not needed on the transaction
334 Api.prototype.deleteTransactionExtensionObjects = function (transaction) {
335 delete transaction.resource_payer;
336 return transaction;
337 };
338 /** Convert actions to hex */
339 Api.prototype.serializeActions = function (actions) {
340 return __awaiter(this, void 0, void 0, function () {
341 var _this = this;
342 return __generator(this, function (_a) {
343 switch (_a.label) {
344 case 0: return [4 /*yield*/, Promise.all(actions.map(function (action) { return __awaiter(_this, void 0, void 0, function () {
345 var account, name, authorization, data, contract;
346 return __generator(this, function (_a) {
347 switch (_a.label) {
348 case 0:
349 account = action.account, name = action.name, authorization = action.authorization, data = action.data;
350 return [4 /*yield*/, this.getContract(account)];
351 case 1:
352 contract = _a.sent();
353 if (typeof data !== 'object') {
354 return [2 /*return*/, action];
355 }
356 return [2 /*return*/, ser.serializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)];
357 }
358 });
359 }); }))];
360 case 1: return [2 /*return*/, _a.sent()];
361 }
362 });
363 });
364 };
365 /** Convert actions from hex */
366 Api.prototype.deserializeActions = function (actions) {
367 return __awaiter(this, void 0, void 0, function () {
368 var _this = this;
369 return __generator(this, function (_a) {
370 switch (_a.label) {
371 case 0: return [4 /*yield*/, Promise.all(actions.map(function (_a) {
372 var account = _a.account, name = _a.name, authorization = _a.authorization, data = _a.data;
373 return __awaiter(_this, void 0, void 0, function () {
374 var contract;
375 return __generator(this, function (_b) {
376 switch (_b.label) {
377 case 0: return [4 /*yield*/, this.getContract(account)];
378 case 1:
379 contract = _b.sent();
380 return [2 /*return*/, ser.deserializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)];
381 }
382 });
383 });
384 }))];
385 case 1: return [2 /*return*/, _a.sent()];
386 }
387 });
388 });
389 };
390 /** Convert a transaction from binary. Also deserializes actions. */
391 Api.prototype.deserializeTransactionWithActions = function (transaction) {
392 return __awaiter(this, void 0, void 0, function () {
393 var deserializedTransaction, deserializedCFActions, deserializedActions;
394 return __generator(this, function (_a) {
395 switch (_a.label) {
396 case 0:
397 if (typeof transaction === 'string') {
398 transaction = ser.hexToUint8Array(transaction);
399 }
400 deserializedTransaction = this.deserializeTransaction(transaction);
401 return [4 /*yield*/, this.deserializeActions(deserializedTransaction.context_free_actions)];
402 case 1:
403 deserializedCFActions = _a.sent();
404 return [4 /*yield*/, this.deserializeActions(deserializedTransaction.actions)];
405 case 2:
406 deserializedActions = _a.sent();
407 return [2 /*return*/, __assign(__assign({}, deserializedTransaction), { context_free_actions: deserializedCFActions, actions: deserializedActions })];
408 }
409 });
410 });
411 };
412 /** Deflate a serialized object */
413 Api.prototype.deflateSerializedArray = function (serializedArray) {
414 return pako_1.deflate(serializedArray, { level: 9 });
415 };
416 /** Inflate a compressed serialized object */
417 Api.prototype.inflateSerializedArray = function (compressedSerializedArray) {
418 return pako_1.inflate(compressedSerializedArray);
419 };
420 /**
421 * Create and optionally broadcast a transaction.
422 *
423 * Named Parameters:
424 * `broadcast`: broadcast this transaction?
425 * `sign`: sign this transaction?
426 * `compression`: compress this transaction?
427 * `readOnlyTrx`: read only transaction?
428 * `returnFailureTraces`: return failure traces? (only available for read only transactions currently)
429 *
430 * If both `blocksBehind` and `expireSeconds` are present,
431 * then fetch the block which is `blocksBehind` behind head block,
432 * use it as a reference for TAPoS, and expire the transaction `expireSeconds` after that block's time.
433 *
434 * If both `useLastIrreversible` and `expireSeconds` are present,
435 * then fetch the last irreversible block, use it as a reference for TAPoS,
436 * and expire the transaction `expireSeconds` after that block's time.
437 *
438 * @returns node response if `broadcast`, `{signatures, serializedTransaction}` if `!broadcast`
439 */
440 Api.prototype.transact = function (transaction, _a) {
441 var _b = _a === void 0 ? {} : _a, _c = _b.broadcast, broadcast = _c === void 0 ? true : _c, _d = _b.sign, sign = _d === void 0 ? true : _d, readOnlyTrx = _b.readOnlyTrx, returnFailureTraces = _b.returnFailureTraces, requiredKeys = _b.requiredKeys, compression = _b.compression, blocksBehind = _b.blocksBehind, useLastIrreversible = _b.useLastIrreversible, expireSeconds = _b.expireSeconds;
442 return __awaiter(this, void 0, void 0, function () {
443 var info, abis, _e, serializedTransaction, serializedContextFreeData, pushTransactionArgs, availableKeys;
444 var _f;
445 return __generator(this, function (_g) {
446 switch (_g.label) {
447 case 0:
448 if (typeof blocksBehind === 'number' && useLastIrreversible) {
449 throw new Error('Use either blocksBehind or useLastIrreversible');
450 }
451 if (!!this.chainId) return [3 /*break*/, 2];
452 return [4 /*yield*/, this.rpc.get_info()];
453 case 1:
454 info = _g.sent();
455 this.chainId = info.chain_id;
456 _g.label = 2;
457 case 2:
458 if (!((typeof blocksBehind === 'number' || useLastIrreversible) && expireSeconds)) return [3 /*break*/, 4];
459 return [4 /*yield*/, this.generateTapos(info, transaction, blocksBehind, useLastIrreversible, expireSeconds)];
460 case 3:
461 transaction = _g.sent();
462 _g.label = 4;
463 case 4:
464 if (!this.hasRequiredTaposFields(transaction)) {
465 throw new Error('Required configuration or TAPOS fields are not present');
466 }
467 return [4 /*yield*/, this.getTransactionAbis(transaction)];
468 case 5:
469 abis = _g.sent();
470 _e = [__assign({}, transaction)];
471 _f = {};
472 return [4 /*yield*/, this.serializeTransactionExtensions(transaction)];
473 case 6:
474 _f.transaction_extensions = _g.sent();
475 return [4 /*yield*/, this.serializeActions(transaction.context_free_actions || [])];
476 case 7:
477 _f.context_free_actions = _g.sent();
478 return [4 /*yield*/, this.serializeActions(transaction.actions)];
479 case 8:
480 transaction = __assign.apply(void 0, _e.concat([(_f.actions = _g.sent(), _f)]));
481 transaction = this.deleteTransactionExtensionObjects(transaction);
482 serializedTransaction = this.serializeTransaction(transaction);
483 serializedContextFreeData = this.serializeContextFreeData(transaction.context_free_data);
484 pushTransactionArgs = {
485 serializedTransaction: serializedTransaction,
486 serializedContextFreeData: serializedContextFreeData,
487 signatures: []
488 };
489 if (!sign) return [3 /*break*/, 13];
490 if (!!requiredKeys) return [3 /*break*/, 11];
491 return [4 /*yield*/, this.signatureProvider.getAvailableKeys()];
492 case 9:
493 availableKeys = _g.sent();
494 return [4 /*yield*/, this.authorityProvider.getRequiredKeys({ transaction: transaction, availableKeys: availableKeys })];
495 case 10:
496 requiredKeys = _g.sent();
497 _g.label = 11;
498 case 11: return [4 /*yield*/, this.signatureProvider.sign({
499 chainId: this.chainId,
500 requiredKeys: requiredKeys,
501 serializedTransaction: serializedTransaction,
502 serializedContextFreeData: serializedContextFreeData,
503 abis: abis,
504 })];
505 case 12:
506 pushTransactionArgs = _g.sent();
507 _g.label = 13;
508 case 13:
509 if (broadcast) {
510 if (compression) {
511 return [2 /*return*/, this.pushCompressedSignedTransaction(pushTransactionArgs, readOnlyTrx, returnFailureTraces)];
512 }
513 return [2 /*return*/, this.pushSignedTransaction(pushTransactionArgs, readOnlyTrx, returnFailureTraces)];
514 }
515 return [2 /*return*/, pushTransactionArgs];
516 }
517 });
518 });
519 };
520 Api.prototype.query = function (account, short, query, _a) {
521 var sign = _a.sign, requiredKeys = _a.requiredKeys, _b = _a.authorization, authorization = _b === void 0 ? [] : _b;
522 return __awaiter(this, void 0, void 0, function () {
523 var info, refBlock, queryBuffer, transaction, serializedTransaction, signatures, abis, availableKeys, signResponse, response, returnBuffer;
524 return __generator(this, function (_c) {
525 switch (_c.label) {
526 case 0: return [4 /*yield*/, this.rpc.get_info()];
527 case 1:
528 info = _c.sent();
529 return [4 /*yield*/, this.tryRefBlockFromGetInfo(info)];
530 case 2:
531 refBlock = _c.sent();
532 queryBuffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder });
533 ser.serializeQuery(queryBuffer, query);
534 transaction = __assign(__assign({}, ser.transactionHeader(refBlock, 60 * 30)), { context_free_actions: [], actions: [{
535 account: account,
536 name: 'queryit',
537 authorization: authorization,
538 data: ser.arrayToHex(queryBuffer.asUint8Array()),
539 }] });
540 serializedTransaction = this.serializeTransaction(transaction);
541 signatures = [];
542 if (!sign) return [3 /*break*/, 8];
543 return [4 /*yield*/, this.getTransactionAbis(transaction)];
544 case 3:
545 abis = _c.sent();
546 if (!!requiredKeys) return [3 /*break*/, 6];
547 return [4 /*yield*/, this.signatureProvider.getAvailableKeys()];
548 case 4:
549 availableKeys = _c.sent();
550 return [4 /*yield*/, this.authorityProvider.getRequiredKeys({ transaction: transaction, availableKeys: availableKeys })];
551 case 5:
552 requiredKeys = _c.sent();
553 _c.label = 6;
554 case 6: return [4 /*yield*/, this.signatureProvider.sign({
555 chainId: this.chainId,
556 requiredKeys: requiredKeys,
557 serializedTransaction: serializedTransaction,
558 serializedContextFreeData: null,
559 abis: abis,
560 })];
561 case 7:
562 signResponse = _c.sent();
563 signatures = signResponse.signatures;
564 _c.label = 8;
565 case 8: return [4 /*yield*/, this.rpc.send_transaction({
566 signatures: signatures,
567 compression: 0,
568 serializedTransaction: serializedTransaction
569 })];
570 case 9:
571 response = _c.sent();
572 returnBuffer = new ser.SerialBuffer({
573 textEncoder: this.textEncoder,
574 textDecoder: this.textDecoder,
575 array: ser.hexToUint8Array(response.processed.action_traces[0][1].return_value)
576 });
577 if (short) {
578 return [2 /*return*/, ser.deserializeAnyvarShort(returnBuffer)];
579 }
580 else {
581 return [2 /*return*/, ser.deserializeAnyvar(returnBuffer)];
582 }
583 return [2 /*return*/];
584 }
585 });
586 });
587 };
588 /** Broadcast a signed transaction */
589 Api.prototype.pushSignedTransaction = function (_a, readOnlyTrx, returnFailureTraces) {
590 var signatures = _a.signatures, serializedTransaction = _a.serializedTransaction, serializedContextFreeData = _a.serializedContextFreeData;
591 if (readOnlyTrx === void 0) { readOnlyTrx = false; }
592 if (returnFailureTraces === void 0) { returnFailureTraces = false; }
593 return __awaiter(this, void 0, void 0, function () {
594 return __generator(this, function (_b) {
595 if (readOnlyTrx) {
596 return [2 /*return*/, this.rpc.push_ro_transaction({
597 signatures: signatures,
598 serializedTransaction: serializedTransaction,
599 serializedContextFreeData: serializedContextFreeData,
600 }, returnFailureTraces)];
601 }
602 return [2 /*return*/, this.rpc.push_transaction({
603 signatures: signatures,
604 serializedTransaction: serializedTransaction,
605 serializedContextFreeData: serializedContextFreeData
606 })];
607 });
608 });
609 };
610 Api.prototype.pushCompressedSignedTransaction = function (_a, readOnlyTrx, returnFailureTraces) {
611 var signatures = _a.signatures, serializedTransaction = _a.serializedTransaction, serializedContextFreeData = _a.serializedContextFreeData;
612 if (readOnlyTrx === void 0) { readOnlyTrx = false; }
613 if (returnFailureTraces === void 0) { returnFailureTraces = false; }
614 return __awaiter(this, void 0, void 0, function () {
615 var compressedSerializedTransaction, compressedSerializedContextFreeData;
616 return __generator(this, function (_b) {
617 compressedSerializedTransaction = this.deflateSerializedArray(serializedTransaction);
618 compressedSerializedContextFreeData = this.deflateSerializedArray(serializedContextFreeData || new Uint8Array(0));
619 if (readOnlyTrx) {
620 return [2 /*return*/, this.rpc.push_ro_transaction({
621 signatures: signatures,
622 compression: 1,
623 serializedTransaction: compressedSerializedTransaction,
624 serializedContextFreeData: compressedSerializedContextFreeData
625 }, returnFailureTraces)];
626 }
627 return [2 /*return*/, this.rpc.push_transaction({
628 signatures: signatures,
629 compression: 1,
630 serializedTransaction: compressedSerializedTransaction,
631 serializedContextFreeData: compressedSerializedContextFreeData
632 })];
633 });
634 });
635 };
636 Api.prototype.generateTapos = function (info, transaction, blocksBehind, useLastIrreversible, expireSeconds) {
637 return __awaiter(this, void 0, void 0, function () {
638 var block, taposBlockNumber, refBlock, _a;
639 return __generator(this, function (_b) {
640 switch (_b.label) {
641 case 0:
642 if (!!info) return [3 /*break*/, 2];
643 return [4 /*yield*/, this.rpc.get_info()];
644 case 1:
645 info = _b.sent();
646 _b.label = 2;
647 case 2:
648 if (!useLastIrreversible) return [3 /*break*/, 4];
649 return [4 /*yield*/, this.tryRefBlockFromGetInfo(info)];
650 case 3:
651 block = _b.sent();
652 return [2 /*return*/, __assign(__assign({}, ser.transactionHeader(block, expireSeconds)), transaction)];
653 case 4:
654 taposBlockNumber = info.head_block_num - blocksBehind;
655 if (!(taposBlockNumber <= info.last_irreversible_block_num)) return [3 /*break*/, 6];
656 return [4 /*yield*/, this.tryGetBlockInfo(taposBlockNumber)];
657 case 5:
658 _a = _b.sent();
659 return [3 /*break*/, 8];
660 case 6: return [4 /*yield*/, this.tryGetBlockHeaderState(taposBlockNumber)];
661 case 7:
662 _a = _b.sent();
663 _b.label = 8;
664 case 8:
665 refBlock = _a;
666 return [2 /*return*/, __assign(__assign({}, ser.transactionHeader(refBlock, expireSeconds)), transaction)];
667 }
668 });
669 });
670 };
671 // eventually break out into TransactionValidator class
672 Api.prototype.hasRequiredTaposFields = function (_a) {
673 var expiration = _a.expiration, ref_block_num = _a.ref_block_num, ref_block_prefix = _a.ref_block_prefix;
674 return !!(expiration && typeof (ref_block_num) === 'number' && typeof (ref_block_prefix) === 'number');
675 };
676 Api.prototype.tryGetBlockHeaderState = function (taposBlockNumber) {
677 return __awaiter(this, void 0, void 0, function () {
678 var error_1;
679 return __generator(this, function (_a) {
680 switch (_a.label) {
681 case 0:
682 _a.trys.push([0, 2, , 4]);
683 return [4 /*yield*/, this.rpc.get_block_header_state(taposBlockNumber)];
684 case 1: return [2 /*return*/, _a.sent()];
685 case 2:
686 error_1 = _a.sent();
687 return [4 /*yield*/, this.tryGetBlockInfo(taposBlockNumber)];
688 case 3: return [2 /*return*/, _a.sent()];
689 case 4: return [2 /*return*/];
690 }
691 });
692 });
693 };
694 Api.prototype.tryGetBlockInfo = function (blockNumber) {
695 return __awaiter(this, void 0, void 0, function () {
696 var error_2;
697 return __generator(this, function (_a) {
698 switch (_a.label) {
699 case 0:
700 _a.trys.push([0, 2, , 4]);
701 return [4 /*yield*/, this.rpc.get_block_info(blockNumber)];
702 case 1: return [2 /*return*/, _a.sent()];
703 case 2:
704 error_2 = _a.sent();
705 return [4 /*yield*/, this.rpc.get_block(blockNumber)];
706 case 3: return [2 /*return*/, _a.sent()];
707 case 4: return [2 /*return*/];
708 }
709 });
710 });
711 };
712 Api.prototype.tryRefBlockFromGetInfo = function (info) {
713 return __awaiter(this, void 0, void 0, function () {
714 var block;
715 return __generator(this, function (_a) {
716 switch (_a.label) {
717 case 0:
718 if (!(info.hasOwnProperty('last_irreversible_block_id') &&
719 info.hasOwnProperty('last_irreversible_block_num') &&
720 info.hasOwnProperty('last_irreversible_block_time'))) return [3 /*break*/, 1];
721 return [2 /*return*/, {
722 block_num: info.last_irreversible_block_num,
723 id: info.last_irreversible_block_id,
724 timestamp: info.last_irreversible_block_time,
725 }];
726 case 1: return [4 /*yield*/, this.tryGetBlockInfo(info.last_irreversible_block_num)];
727 case 2:
728 block = _a.sent();
729 return [2 /*return*/, {
730 block_num: block.block_num,
731 id: block.id,
732 timestamp: block.timestamp,
733 }];
734 }
735 });
736 });
737 };
738 Api.prototype.with = function (accountName) {
739 return new ActionBuilder(this, accountName);
740 };
741 Api.prototype.buildTransaction = function (cb) {
742 var tx = new TransactionBuilder(this);
743 if (cb) {
744 return cb(tx);
745 }
746 return tx;
747 };
748 return Api;
749}()); // Api
750exports.Api = Api;
751var TransactionBuilder = /** @class */ (function () {
752 function TransactionBuilder(api) {
753 this.actions = [];
754 this.contextFreeGroups = [];
755 this.api = api;
756 }
757 TransactionBuilder.prototype.with = function (accountName) {
758 var actionBuilder = new ActionBuilder(this.api, accountName);
759 this.actions.push(actionBuilder);
760 return actionBuilder;
761 };
762 TransactionBuilder.prototype.associateContextFree = function (contextFreeGroup) {
763 this.contextFreeGroups.push(contextFreeGroup);
764 return this;
765 };
766 TransactionBuilder.prototype.send = function (config) {
767 return __awaiter(this, void 0, void 0, function () {
768 var contextFreeDataSet, contextFreeActions, actions;
769 var _this = this;
770 return __generator(this, function (_a) {
771 switch (_a.label) {
772 case 0:
773 contextFreeDataSet = [];
774 contextFreeActions = [];
775 actions = this.actions.map(function (actionBuilder) { return actionBuilder.serializedData; });
776 return [4 /*yield*/, Promise.all(this.contextFreeGroups.map(function (contextFreeCallback) { return __awaiter(_this, void 0, void 0, function () {
777 var _a, action, contextFreeAction, contextFreeData;
778 return __generator(this, function (_b) {
779 _a = contextFreeCallback({
780 cfd: contextFreeDataSet.length,
781 cfa: contextFreeActions.length
782 }), action = _a.action, contextFreeAction = _a.contextFreeAction, contextFreeData = _a.contextFreeData;
783 if (action) {
784 actions.push(action);
785 }
786 if (contextFreeAction) {
787 contextFreeActions.push(contextFreeAction);
788 }
789 if (contextFreeData) {
790 contextFreeDataSet.push(contextFreeData);
791 }
792 return [2 /*return*/];
793 });
794 }); }))];
795 case 1:
796 _a.sent();
797 this.contextFreeGroups = [];
798 this.actions = [];
799 return [4 /*yield*/, this.api.transact({
800 context_free_data: contextFreeDataSet,
801 context_free_actions: contextFreeActions,
802 actions: actions
803 }, config)];
804 case 2: return [2 /*return*/, _a.sent()];
805 }
806 });
807 });
808 };
809 return TransactionBuilder;
810}());
811exports.TransactionBuilder = TransactionBuilder;
812var ActionBuilder = /** @class */ (function () {
813 function ActionBuilder(api, accountName) {
814 this.api = api;
815 this.accountName = accountName;
816 }
817 ActionBuilder.prototype.as = function (actorName) {
818 if (actorName === void 0) { actorName = []; }
819 var authorization = [];
820 if (actorName && typeof actorName === 'string') {
821 authorization = [{ actor: actorName, permission: 'active' }];
822 }
823 else {
824 authorization = actorName;
825 }
826 return new ActionSerializer(this, this.api, this.accountName, authorization);
827 };
828 return ActionBuilder;
829}());
830exports.ActionBuilder = ActionBuilder;
831var ActionSerializer = /** @class */ (function () {
832 function ActionSerializer(parent, api, accountName, authorization) {
833 var e_4, _a;
834 var _this = this;
835 var jsonAbi = api.cachedAbis.get(accountName);
836 if (!jsonAbi) {
837 throw new Error('ABI must be cached before using ActionBuilder, run api.getAbi()');
838 }
839 var types = ser.getTypesFromAbi(ser.createInitialTypes(), jsonAbi.abi);
840 var actions = new Map();
841 try {
842 for (var _b = __values(jsonAbi.abi.actions), _c = _b.next(); !_c.done; _c = _b.next()) {
843 var _d = _c.value, name_2 = _d.name, type = _d.type;
844 actions.set(name_2, ser.getType(types, type));
845 }
846 }
847 catch (e_4_1) { e_4 = { error: e_4_1 }; }
848 finally {
849 try {
850 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
851 }
852 finally { if (e_4) throw e_4.error; }
853 }
854 actions.forEach(function (type, name) {
855 var _a;
856 Object.assign(_this, (_a = {},
857 _a[name] = function () {
858 var args = [];
859 for (var _i = 0; _i < arguments.length; _i++) {
860 args[_i] = arguments[_i];
861 }
862 var data = {};
863 args.forEach(function (arg, index) {
864 var field = type.fields[index];
865 data[field.name] = arg;
866 });
867 var serializedData = ser.serializeAction({ types: types, actions: actions }, accountName, name, authorization, data, api.textEncoder, api.textDecoder);
868 parent.serializedData = serializedData;
869 return serializedData;
870 },
871 _a));
872 });
873 }
874 return ActionSerializer;
875}());
876//# sourceMappingURL=eosjs-api.js.map
\No newline at end of file