UNPKG

@fioprotocol/fiojs

Version:

FioJS is a Utility SDK for packing, signing and encryption functionality for the FIO blockchain. It is used by the FIO TypeScript SDK

474 lines 23.9 kB
"use strict"; /** * @module FIO */ // copyright defined in fiojs/LICENSE.txt var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(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); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } }; 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; }; var __read = (this && this.__read) || function (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; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __values = (this && this.__values) || function(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."); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.signAllAuthorityProvider = exports.Api = void 0; var ser = __importStar(require("./chain-serialize")); var abiAbi = require("../src/abi.abi.json"); var transactionAbi = require("../src/transaction.abi.json"); var Api = /** @class */ (function () { /** * @param args * * `authorityProvider`: Get public keys needed to meet authorities in a transaction * * `abiProvider`: Supplies ABIs in raw form (binary) * * `signatureProvider`: Signs transactions * * `chainId`: Identifies chain * * `textEncoder`: `TextEncoder` instance to use. Pass in `null` if running in a browser * * `textDecoder`: `TextDecoder` instance to use. Pass in `null` if running in a browser */ function Api(args) { /** Holds information needed to serialize contract actions */ this.contracts = new Map(); /** Fetched abis */ this.cachedAbis = new Map(); this.authorityProvider = args.authorityProvider; this.abiProvider = args.abiProvider; this.signatureProvider = args.signatureProvider; this.chainId = args.chainId; this.textEncoder = args.textEncoder; this.textDecoder = args.textDecoder; this.abiTypes = ser.getTypesFromAbi(ser.createInitialTypes(), abiAbi); this.transactionTypes = ser.getTypesFromAbi(ser.createInitialTypes(), transactionAbi); } /** Decodes an abi as Uint8Array into json. */ Api.prototype.rawAbiToJson = function (rawAbi) { var buffer = new ser.SerialBuffer({ array: rawAbi, textDecoder: this.textDecoder, textEncoder: this.textEncoder, }); if (!ser.supportedAbiVersion(buffer.getString())) { throw new Error("Unsupported abi version"); } buffer.restartRead(); return this.abiTypes.get("abi_def").deserialize(buffer); }; /** Get abi in both binary and structured forms. Reload from AbiProvider when needed. */ Api.prototype.getCachedAbi = function (accountName, reload) { if (reload === void 0) { reload = false; } return __awaiter(this, void 0, void 0, function () { var cachedAbi, rawAbi, abi, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!reload && this.cachedAbis.get(accountName)) { return [2 /*return*/, this.cachedAbis.get(accountName)]; } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.abiProvider.getRawAbi(accountName)]; case 2: rawAbi = (_a.sent()).abi; abi = this.rawAbiToJson(rawAbi); cachedAbi = { rawAbi: rawAbi, abi: abi }; return [3 /*break*/, 4]; case 3: e_1 = _a.sent(); e_1.message = "abiProvider for ".concat(accountName, ": ").concat(e_1.message); throw e_1; case 4: if (!cachedAbi) { throw new Error("Missing abi for ".concat(accountName)); } this.cachedAbis.set(accountName, cachedAbi); return [2 /*return*/, cachedAbi]; } }); }); }; /** Get abi in structured form. Reload from AbiProvider when needed. */ Api.prototype.getAbi = function (accountName, reload) { if (reload === void 0) { reload = false; } return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.getCachedAbi(accountName, reload)]; case 1: return [2 /*return*/, (_a.sent()).abi]; } }); }); }; /** Get abis needed by a transaction */ Api.prototype.getTransactionAbis = function (transaction, reload) { if (reload === void 0) { reload = false; } return __awaiter(this, void 0, void 0, function () { var actions, accounts, uniqueAccounts, actionPromises; var _this = this; return __generator(this, function (_a) { actions = (transaction.context_free_actions || []).concat(transaction.actions); accounts = actions.map(function (action) { return action.account; }); uniqueAccounts = new Set(accounts); actionPromises = __spreadArray([], __read(uniqueAccounts), false).map(function (account) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = {}; return [4 /*yield*/, this.getCachedAbi(account, reload)]; case 1: return [2 /*return*/, (_a.abi = (_b.sent()).rawAbi, _a.accountName = account, _a)]; } }); }); }); return [2 /*return*/, Promise.all(actionPromises)]; }); }); }; /** Get data needed to serialize actions in a contract */ Api.prototype.getContract = function (accountName, reload) { if (reload === void 0) { reload = false; } return __awaiter(this, void 0, void 0, function () { var abi, types, actions, _a, _b, _c, name_1, type, result; var e_2, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: if (!reload && this.contracts.get(accountName)) { return [2 /*return*/, this.contracts.get(accountName)]; } return [4 /*yield*/, this.getAbi(accountName, reload)]; case 1: abi = _e.sent(); types = ser.getTypesFromAbi(ser.createInitialTypes(), abi); actions = new Map(); try { for (_a = __values(abi.actions), _b = _a.next(); !_b.done; _b = _a.next()) { _c = _b.value, name_1 = _c.name, type = _c.type; actions.set(name_1, ser.getType(types, type)); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_b && !_b.done && (_d = _a.return)) _d.call(_a); } finally { if (e_2) throw e_2.error; } } result = { types: types, actions: actions }; this.contracts.set(accountName, result); return [2 /*return*/, result]; } }); }); }; /** Convert `value` to binary form. `type` must be a built-in abi type or in `transaction.abi.json`. */ Api.prototype.serialize = function (buffer, type, value) { this.transactionTypes.get(type).serialize(buffer, value); }; /** Convert data in `buffer` to structured form. `type` must be a built-in abi type or in `transaction.abi.json`. */ Api.prototype.deserialize = function (buffer, type) { return this.transactionTypes.get(type).deserialize(buffer); }; /** Convert a transaction to binary */ Api.prototype.serializeTransaction = function (transaction) { var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder }); this.serialize(buffer, "transaction", __assign({ actions: [], context_free_actions: [], delay_sec: 0, max_cpu_usage_ms: 0, max_net_usage_words: 0, transaction_extensions: [] }, transaction)); return buffer.asUint8Array(); }; /** Serialize context-free data */ Api.prototype.serializeContextFreeData = function (contextFreeData) { var e_3, _a; if (!contextFreeData || !contextFreeData.length) { return null; } var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder }); buffer.pushVaruint32(contextFreeData.length); try { for (var contextFreeData_1 = __values(contextFreeData), contextFreeData_1_1 = contextFreeData_1.next(); !contextFreeData_1_1.done; contextFreeData_1_1 = contextFreeData_1.next()) { var data = contextFreeData_1_1.value; buffer.pushBytes(data); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (contextFreeData_1_1 && !contextFreeData_1_1.done && (_a = contextFreeData_1.return)) _a.call(contextFreeData_1); } finally { if (e_3) throw e_3.error; } } return buffer.asUint8Array(); }; /** Convert a transaction from binary. Leaves actions in hex. */ Api.prototype.deserializeTransaction = function (transaction) { var buffer = new ser.SerialBuffer({ textEncoder: this.textEncoder, textDecoder: this.textDecoder }); buffer.pushArray(transaction); return this.deserialize(buffer, "transaction"); }; /** Convert actions to hex */ Api.prototype.serializeActions = function (actions) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.all(actions.map(function (_a) { var account = _a.account, name = _a.name, authorization = _a.authorization, data = _a.data; return __awaiter(_this, void 0, void 0, function () { var contract; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.getContract(account)]; case 1: contract = _b.sent(); return [2 /*return*/, ser.serializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)]; } }); }); }))]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; /** Convert actions from hex */ Api.prototype.deserializeActions = function (actions) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.all(actions.map(function (_a) { var account = _a.account, name = _a.name, authorization = _a.authorization, data = _a.data; return __awaiter(_this, void 0, void 0, function () { var contract; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.getContract(account)]; case 1: contract = _b.sent(); return [2 /*return*/, ser.deserializeAction(contract, account, name, authorization, data, this.textEncoder, this.textDecoder)]; } }); }); }))]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; /** Convert a transaction from binary. Also deserializes actions. */ Api.prototype.deserializeTransactionWithActions = function (transaction) { return __awaiter(this, void 0, void 0, function () { var deserializedTransaction, deserializedCFActions, deserializedActions; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof transaction === "string") { transaction = ser.hexToUint8Array(transaction); } deserializedTransaction = this.deserializeTransaction(transaction); return [4 /*yield*/, this.deserializeActions(deserializedTransaction.context_free_actions)]; case 1: deserializedCFActions = _a.sent(); return [4 /*yield*/, this.deserializeActions(deserializedTransaction.actions)]; case 2: deserializedActions = _a.sent(); return [2 /*return*/, __assign(__assign({}, deserializedTransaction), { actions: deserializedActions, context_free_actions: deserializedCFActions })]; } }); }); }; /** * Create a transaction. * * Named Parameters: * * `sign`: sign this transaction? * @returns `{signatures, serializedTransaction}` */ Api.prototype.transact = function (transaction, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.sign, sign = _c === void 0 ? true : _c; return __awaiter(this, void 0, void 0, function () { var abis, _d, serializedTransaction, serializedContextFreeData, pushTransactionArgs, availableKeys, requiredKeys; var _e; return __generator(this, function (_f) { switch (_f.label) { case 0: if (!this.hasRequiredTaposFields(transaction)) { throw new Error("Required configuration or TAPOS fields are not present"); } return [4 /*yield*/, this.getTransactionAbis(transaction)]; case 1: abis = _f.sent(); _d = [__assign({}, transaction)]; _e = {}; return [4 /*yield*/, this.serializeActions(transaction.actions)]; case 2: _e.actions = _f.sent(); return [4 /*yield*/, this.serializeActions(transaction.context_free_actions || [])]; case 3: transaction = __assign.apply(void 0, _d.concat([(_e.context_free_actions = _f.sent(), _e)])); serializedTransaction = this.serializeTransaction(transaction); serializedContextFreeData = this.serializeContextFreeData(transaction.context_free_data); pushTransactionArgs = { serializedContextFreeData: serializedContextFreeData, serializedTransaction: serializedTransaction, signatures: [], }; if (!sign) return [3 /*break*/, 7]; return [4 /*yield*/, this.signatureProvider.getAvailableKeys()]; case 4: availableKeys = _f.sent(); return [4 /*yield*/, this.authorityProvider.getRequiredKeys({ transaction: transaction, availableKeys: availableKeys })]; case 5: requiredKeys = _f.sent(); return [4 /*yield*/, this.signatureProvider.sign({ abis: abis, chainId: this.chainId, requiredKeys: requiredKeys, serializedContextFreeData: serializedContextFreeData, serializedTransaction: serializedTransaction, })]; case 6: pushTransactionArgs = _f.sent(); _f.label = 7; case 7: return [2 /*return*/, pushTransactionArgs]; } }); }); }; // eventually break out into TransactionValidator class Api.prototype.hasRequiredTaposFields = function (_a) { var expiration = _a.expiration, ref_block_num = _a.ref_block_num, ref_block_prefix = _a.ref_block_prefix, transaction = __rest(_a, ["expiration", "ref_block_num", "ref_block_prefix"]); return !!(expiration && ref_block_num && ref_block_prefix); }; return Api; }()); // Api exports.Api = Api; /** * Simple authority provider that signs with all provided keys. * * If their more availableKeys than are required to sign then the get_required_keys * rpc call is required to filter them (tests/chain-jsonrpc.ts * getRequiredKeys(authorityProviderArgs)) */ exports.signAllAuthorityProvider = { getRequiredKeys: function (authorityProviderArgs) { return __awaiter(this, void 0, void 0, function () { var availableKeys; return __generator(this, function (_a) { availableKeys = authorityProviderArgs.availableKeys; return [2 /*return*/, availableKeys]; }); }); }, }; //# sourceMappingURL=chain-api.js.map