Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@zilliqa-js/core

Package Overview
Dependencies
Maintainers
5
Versions
75
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@zilliqa-js/core - npm Package Compare versions

Comparing version 3.4.2-rc.0 to 3.4.2

1192

dist/esm/bundle.js

@@ -1,1191 +0,1 @@

// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
var Signer = /** @class */ (function () {
function Signer() {
}
return Signer;
}());
var TransactionError;
(function (TransactionError) {
TransactionError[TransactionError["CHECKER_FAILED"] = 0] = "CHECKER_FAILED";
TransactionError[TransactionError["RUNNER_FAILED"] = 1] = "RUNNER_FAILED";
TransactionError[TransactionError["BALANCE_TRANSFER_FAILED"] = 2] = "BALANCE_TRANSFER_FAILED";
TransactionError[TransactionError["EXECUTE_CMD_FAILED"] = 3] = "EXECUTE_CMD_FAILED";
TransactionError[TransactionError["EXECUTE_CMD_TIMEOUT"] = 4] = "EXECUTE_CMD_TIMEOUT";
TransactionError[TransactionError["NO_GAS_REMAINING_FOUND"] = 5] = "NO_GAS_REMAINING_FOUND";
TransactionError[TransactionError["NO_ACCEPTED_FOUND"] = 6] = "NO_ACCEPTED_FOUND";
TransactionError[TransactionError["CALL_CONTRACT_FAILED"] = 7] = "CALL_CONTRACT_FAILED";
TransactionError[TransactionError["CREATE_CONTRACT_FAILED"] = 8] = "CREATE_CONTRACT_FAILED";
TransactionError[TransactionError["JSON_OUTPUT_CORRUPTED"] = 9] = "JSON_OUTPUT_CORRUPTED";
TransactionError[TransactionError["CONTRACT_NOT_EXIST"] = 10] = "CONTRACT_NOT_EXIST";
TransactionError[TransactionError["STATE_CORRUPTED"] = 11] = "STATE_CORRUPTED";
TransactionError[TransactionError["LOG_ENTRY_INSTALL_FAILED"] = 12] = "LOG_ENTRY_INSTALL_FAILED";
TransactionError[TransactionError["MESSAGE_CORRUPTED"] = 13] = "MESSAGE_CORRUPTED";
TransactionError[TransactionError["RECEIPT_IS_NULL"] = 14] = "RECEIPT_IS_NULL";
TransactionError[TransactionError["MAX_DEPTH_REACHED"] = 15] = "MAX_DEPTH_REACHED";
TransactionError[TransactionError["CHAIN_CALL_DIFF_SHARD"] = 16] = "CHAIN_CALL_DIFF_SHARD";
TransactionError[TransactionError["PREPARATION_FAILED"] = 17] = "PREPARATION_FAILED";
TransactionError[TransactionError["NO_OUTPUT"] = 18] = "NO_OUTPUT";
TransactionError[TransactionError["OUTPUT_ILLEGAL"] = 19] = "OUTPUT_ILLEGAL";
})(TransactionError || (TransactionError = {}));
/******************************************************************************
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) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
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 __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 (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 };
}
}
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 __spreadArray(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));
}
// Copyright (C) 2018 Zilliqa
/**
* sign
*
* This decorates a method by attempting to sign the first argument of the
* intercepted method.
*
* @param {T} target
* @param {K} key
* @param {PropertyDescriptor} descriptor
* @returns {PropertyDescriptor | undefined}
*/
var sign = function (target, key, descriptor) {
var original = descriptor.value;
function interceptor(arg) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var signed;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(original && arg.bytes)) return [3 /*break*/, 2];
return [4 /*yield*/, this.signer.sign(arg)];
case 1:
signed = _a.sent();
return [2 /*return*/, original.call.apply(original, __spreadArray([this, signed], __read(args), false))];
case 2: return [2 /*return*/];
}
});
});
}
descriptor.value = interceptor;
return descriptor;
};
(function(self) {
if (self.fetch) {
return
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob();
return true
} catch(e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isDataView = function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
};
var isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {done: value === undefined, value: value}
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
};
}
return iterator
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue+','+value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) { items.push(name); });
return iteratorFor(items)
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) { items.push(value); });
return iteratorFor(items)
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) { items.push([name, value]); });
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
throw new Error('unsupported BodyInit type')
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
};
}
this.json = function() {
return this.text().then(JSON.parse)
};
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return (methods.indexOf(upcased) > -1) ? upcased : method
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'omit';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit })
};
function decode(body) {
var form = new FormData();
body.trim().split('&').forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = 'statusText' in options ? options.statusText : 'OK';
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
};
self.Headers = Headers;
self.Request = Request;
self.Response = Response;
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
};
self.fetch.polyfill = true;
})(typeof self !== 'undefined' ? self : undefined);
/**
* blockchain-side.
*/
var RPCMethod;
(function (RPCMethod) {
// Network-related methods
RPCMethod["GetNetworkId"] = "GetNetworkId";
// Blockchain-related methods
RPCMethod["GetBlockchainInfo"] = "GetBlockchainInfo";
RPCMethod["GetShardingStructure"] = "GetShardingStructure";
RPCMethod["GetDSBlock"] = "GetDsBlock";
RPCMethod["GetLatestDSBlock"] = "GetLatestDsBlock";
RPCMethod["GetNumDSBlocks"] = "GetNumDSBlocks";
RPCMethod["GetDSBlockRate"] = "GetDSBlockRate";
RPCMethod["DSBlockListing"] = "DSBlockListing";
RPCMethod["GetTxBlock"] = "GetTxBlock";
RPCMethod["GetLatestTxBlock"] = "GetLatestTxBlock";
RPCMethod["GetNumTxBlocks"] = "GetNumTxBlocks";
RPCMethod["GetTxBlockRate"] = "GetTxBlockRate";
RPCMethod["TxBlockListing"] = "TxBlockListing";
RPCMethod["GetNumTransactions"] = "GetNumTransactions";
RPCMethod["GetTransactionRate"] = "GetTransactionRate";
RPCMethod["GetCurrentMiniEpoch"] = "GetCurrentMiniEpoch";
RPCMethod["GetCurrentDSEpoch"] = "GetCurrentDSEpoch";
RPCMethod["GetPrevDifficulty"] = "GetPrevDifficulty";
RPCMethod["GetPrevDSDifficulty"] = "GetPrevDSDifficulty";
RPCMethod["GetTotalCoinSupply"] = "GetTotalCoinSupply";
RPCMethod["GetMinerInfo"] = "GetMinerInfo";
// Transaction-related methods
RPCMethod["CreateTransaction"] = "CreateTransaction";
RPCMethod["GetTransaction"] = "GetTransaction";
RPCMethod["GetTransactionStatus"] = "GetTransactionStatus";
RPCMethod["GetRecentTransactions"] = "GetRecentTransactions";
RPCMethod["GetTransactionsForTxBlock"] = "GetTransactionsForTxBlock";
RPCMethod["GetTransactionsForTxBlockEx"] = "GetTransactionsForTxBlockEx";
RPCMethod["GetTxnBodiesForTxBlock"] = "GetTxnBodiesForTxBlock";
RPCMethod["GetTxnBodiesForTxBlockEx"] = "GetTxnBodiesForTxBlockEx";
RPCMethod["GetNumTxnsTxEpoch"] = "GetNumTxnsTxEpoch";
RPCMethod["GetNumTxnsDSEpoch"] = "GetNumTxnsDSEpoch";
RPCMethod["GetMinimumGasPrice"] = "GetMinimumGasPrice";
// Contract-related methods
RPCMethod["GetContractAddressFromTransactionID"] = "GetContractAddressFromTransactionID";
RPCMethod["GetSmartContracts"] = "GetSmartContracts";
RPCMethod["GetSmartContractCode"] = "GetSmartContractCode";
RPCMethod["GetSmartContractInit"] = "GetSmartContractInit";
RPCMethod["GetSmartContractState"] = "GetSmartContractState";
RPCMethod["GetSmartContractSubState"] = "GetSmartContractSubState";
RPCMethod["GetStateProof"] = "GetStateProof";
// Account-related methods
RPCMethod["GetBalance"] = "GetBalance";
})(RPCMethod || (RPCMethod = {}));
var RPCErrorCode;
(function (RPCErrorCode) {
// Standard JSON-RPC 2.0 errors
// RPC_INVALID_REQUEST is internally mapped to HTTP_BAD_REQUEST (400).
// It should not be used for application-layer errors.
RPCErrorCode[RPCErrorCode["RPC_INVALID_REQUEST"] = -32600] = "RPC_INVALID_REQUEST";
// RPC_METHOD_NOT_FOUND is internally mapped to HTTP_NOT_FOUND (404).
// It should not be used for application-layer errors.
RPCErrorCode[RPCErrorCode["RPC_METHOD_NOT_FOUND"] = -32601] = "RPC_METHOD_NOT_FOUND";
RPCErrorCode[RPCErrorCode["RPC_INVALID_PARAMS"] = -32602] = "RPC_INVALID_PARAMS";
// RPC_INTERNAL_ERROR should only be used for genuine errors in bitcoind
// (for example datadir corruption).
RPCErrorCode[RPCErrorCode["RPC_INTERNAL_ERROR"] = -32603] = "RPC_INTERNAL_ERROR";
RPCErrorCode[RPCErrorCode["RPC_PARSE_ERROR"] = -32700] = "RPC_PARSE_ERROR";
// General application defined errors
RPCErrorCode[RPCErrorCode["RPC_MISC_ERROR"] = -1] = "RPC_MISC_ERROR";
RPCErrorCode[RPCErrorCode["RPC_TYPE_ERROR"] = -3] = "RPC_TYPE_ERROR";
RPCErrorCode[RPCErrorCode["RPC_INVALID_ADDRESS_OR_KEY"] = -5] = "RPC_INVALID_ADDRESS_OR_KEY";
RPCErrorCode[RPCErrorCode["RPC_INVALID_PARAMETER"] = -8] = "RPC_INVALID_PARAMETER";
RPCErrorCode[RPCErrorCode["RPC_DATABASE_ERROR"] = -20] = "RPC_DATABASE_ERROR";
RPCErrorCode[RPCErrorCode["RPC_DESERIALIZATION_ERROR"] = -22] = "RPC_DESERIALIZATION_ERROR";
RPCErrorCode[RPCErrorCode["RPC_VERIFY_ERROR"] = -25] = "RPC_VERIFY_ERROR";
RPCErrorCode[RPCErrorCode["RPC_VERIFY_REJECTED"] = -26] = "RPC_VERIFY_REJECTED";
RPCErrorCode[RPCErrorCode["RPC_IN_WARMUP"] = -28] = "RPC_IN_WARMUP";
RPCErrorCode[RPCErrorCode["RPC_METHOD_DEPRECATED"] = -32] = "RPC_METHOD_DEPRECATED";
})(RPCErrorCode || (RPCErrorCode = {}));
var DEFAULT_HEADERS = { "Content-Type": "application/json" };
var performRPC = function (request, handler) { return __awaiter(void 0, void 0, void 0, function () {
var response, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, fetch(request.url, {
method: "POST",
cache: "no-cache",
mode: "cors",
redirect: "follow",
body: JSON.stringify(request.payload),
headers: __assign(__assign({}, DEFAULT_HEADERS), ((request.options && request.options.headers) || {})),
})];
case 1:
response = _a.sent();
return [2 /*return*/, response
.json()
.then(function (body) {
return __assign(__assign({}, body), { req: request });
})
.then(handler)];
case 2:
err_1 = _a.sent();
throw err_1;
case 3: return [2 /*return*/];
}
});
}); };
// identical to performRPC; difference is the response
var performBatchRPC = function (request, handler // eslint-disable-line @typescript-eslint/no-unused-vars
) { return __awaiter(void 0, void 0, void 0, function () {
var response, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, fetch(request.url, {
method: "POST",
cache: "no-cache",
mode: "cors",
redirect: "follow",
referrer: "no-referrer",
body: JSON.stringify(request.payload),
headers: __assign(__assign({}, DEFAULT_HEADERS), ((request.options && request.options.headers) || {})),
})];
case 1:
response = _a.sent();
return [2 /*return*/, (response
.json()
.then(function (batch_result) {
return { batch_result: batch_result, req: request };
})
// no handler as compared to performRPC to preserve the body array
// e.g. response
/*
{ body:
[ { id: 1, jsonrpc: '2.0', result: [Object] },
{ id: 1, jsonrpc: '2.0', result: [Object] } ],
req:
{ url: 'https://dev-api.zilliqa.com',
payload: [ [Object], [Object] ] } }
*/
.then())];
case 2:
err_2 = _a.sent();
throw err_2;
case 3: return [2 /*return*/];
}
});
}); };
// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
function isValidResponse(response) {
if (response.jsonrpc === '2.0' &&
(response.id === '1' || response.id === 1) &&
(response.error || response.result)) {
return true;
}
return false;
}
function composeMiddleware() {
var fns = [];
for (var _i = 0; _i < arguments.length; _i++) {
fns[_i] = arguments[_i];
}
if (fns.length === 0) {
return function (arg) { return arg; };
}
if (fns.length === 1) {
return fns[0];
}
return fns.reduce(function (a, b) { return function (arg) { return a(b(arg)); }; });
}
// Copyright (C) 2018 Zilliqa
var MiddlewareType;
(function (MiddlewareType) {
MiddlewareType[MiddlewareType["REQ"] = 0] = "REQ";
MiddlewareType[MiddlewareType["RES"] = 1] = "RES";
})(MiddlewareType || (MiddlewareType = {}));
var BaseProvider = /** @class */ (function () {
function BaseProvider(nodeURL, reqMiddleware, resMiddleware) {
if (reqMiddleware === void 0) { reqMiddleware = new Map(); }
if (resMiddleware === void 0) { resMiddleware = new Map(); }
var _this = this;
this.middleware = {
request: {
use: function (fn, match) {
if (match === void 0) { match = '*'; }
_this.pushMiddleware(fn, 0 /* MiddlewareType.REQ */, match);
},
},
response: {
use: function (fn, match) {
if (match === void 0) { match = '*'; }
_this.pushMiddleware(fn, 1 /* MiddlewareType.RES */, match);
},
},
};
this.nodeURL = nodeURL;
this.reqMiddleware = reqMiddleware;
this.resMiddleware = resMiddleware;
}
/**
* pushMiddleware
*
* Adds the middleware to the appropriate middleware map.
*
* @param {ResMiddlewareFn}
* @param {T} type
* @param {Matcher} match
* @returns {void}
*/
BaseProvider.prototype.pushMiddleware = function (fn, type, match) {
if (type !== 0 /* MiddlewareType.REQ */ && type !== 1 /* MiddlewareType.RES */) {
throw new Error('Please specify the type of middleware being added');
}
if (type === 0 /* MiddlewareType.REQ */) {
var current = this.reqMiddleware.get(match) || [];
this.reqMiddleware.set(match, __spreadArray(__spreadArray([], __read(current), false), [fn], false));
}
else {
var current = this.resMiddleware.get(match) || [];
this.resMiddleware.set(match, __spreadArray(__spreadArray([], __read(current), false), [fn], false));
}
};
/**
* getMiddleware
*
* Returns the middleware that matches the matcher provided. Note that
* middleware are called in order of specificity: string -> regexp ->
* wildcard.
*
* @param {Matcher} match
* @returns {[ReqMiddlewareFn[], ResMiddlewareFn[]]}
*/
BaseProvider.prototype.getMiddleware = function (method) {
var e_1, _a, e_2, _b;
var reqFns = [];
var resFns = [];
try {
for (var _c = __values(this.reqMiddleware.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), key = _e[0], transformers = _e[1];
if (typeof key === 'string' && key !== '*' && key === method) {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
if (key instanceof RegExp && key.test(method)) {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
if (key === '*') {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
}
}
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; }
}
try {
for (var _f = __values(this.resMiddleware.entries()), _g = _f.next(); !_g.done; _g = _f.next()) {
var _h = __read(_g.value, 2), key = _h[0], transformers = _h[1];
if (typeof key === 'string' && key !== '*' && key === method) {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
if (key instanceof RegExp && key.test(method)) {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
if (key === '*') {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
return [reqFns, resFns];
};
return BaseProvider;
}());
// Copyright (C) 2018 Zilliqa
var HTTPProvider = /** @class */ (function (_super) {
__extends(HTTPProvider, _super);
function HTTPProvider() {
return _super !== null && _super.apply(this, arguments) || this;
}
HTTPProvider.prototype.buildPayload = function (method, params) {
return {
url: this.nodeURL,
payload: { id: 1, jsonrpc: '2.0', method: method, params: params },
};
};
HTTPProvider.prototype.buildBatchPayload = function (method, paramsList) {
var payloads = [];
for (var i = 0; i < paramsList.length; i++) {
// most of the payloads should be a single param, e.g. GetTransaction
// however, there are special cases e.g. GetSmartContractSubState & GetTransactionsForTxBlockEx
// where the param field is a list
var payloadParams = paramsList[i];
var params = void 0;
if (Array.isArray(payloadParams)) {
// for those param field that is already a list
params = payloadParams;
}
else {
params = [payloadParams];
}
// id start from index 1
payloads.push({
id: i + 1,
jsonrpc: '2.0',
method: method,
params: params,
});
}
return {
url: this.nodeURL,
payload: payloads,
};
};
HTTPProvider.prototype.send = function (method) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
var _a = __read(this.getMiddleware(method), 2), tReq = _a[0], tRes = _a[1];
var reqMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tReq), false));
var resMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tRes), false));
var req = reqMiddleware(this.buildPayload(method, params));
return performRPC(req, resMiddleware);
};
HTTPProvider.prototype.sendBatch = function (method, params) {
var _a = __read(this.getMiddleware(method), 2), tReq = _a[0], tRes = _a[1];
var reqMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tReq), false));
composeMiddleware.apply(void 0, __spreadArray([], __read(tRes), false));
var batchPayload = this.buildBatchPayload(method, params);
var req = reqMiddleware(batchPayload);
return performBatchRPC(req);
};
HTTPProvider.prototype.subscribe = function (event, subscriber) {
throw new Error('HTTPProvider does not support subscriptions.');
};
HTTPProvider.prototype.unsubscribe = function (token) {
throw new Error('HTTPProvider does not support subscriptions.');
};
return HTTPProvider;
}(BaseProvider));
// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// this constant is used to indicate the number of times to poll the
// blockchain for a transaction confirmation. this number has been selected by
// using a heuristic to calculate the approximate maximum amount of time it
// should take for a transaction to be confirmed, even during a PoW submission
// round.
var GET_TX_ATTEMPTS = 33;
//
// An event handler can take an optional event argument
// and should not return a value
// An array of all currently registered event handlers for a type
// A map of event types and their corresponding event handlers.
/** Mitt: Tiny (~200b) functional event emitter / pubsub.
* @name mitt
* @returns {Mitt}
*/
function mitt(all ) {
all = all || Object.create(null);
return {
/**
* Register an event handler for the given type.
*
* @param {String} type Type of event to listen for, or `"*"` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
on: function on(type , handler ) {
(all[type] || (all[type] = [])).push(handler);
},
/**
* Remove an event handler for the given type.
*
* @param {String} type Type of event to unregister `handler` from, or `"*"`
* @param {Function} handler Handler function to remove
* @memberOf mitt
*/
off: function off(type , handler ) {
if (all[type]) {
all[type].splice(all[type].indexOf(handler) >>> 0, 1);
}
},
/**
* Invoke all handlers for the given type.
* If present, `"*"` handlers are invoked after type-matched handlers.
*
* @param {String} type The event type to invoke
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
* @memberOf mitt
*/
emit: function emit(type , evt ) {
(all[type] || []).slice().map(function (handler) { handler(evt); });
(all['*'] || []).slice().map(function (handler) { handler(type, evt); });
}
};
}
// Copyright (C) 2018 Zilliqa
var EventEmitter = /** @class */ (function () {
function EventEmitter() {
var _this = this;
this.handlers = {};
// TODO: As any added to solve
// error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
this.emitter = new mitt(this.handlers);
this.off = this.emitter.off.bind(this);
this.emit = this.emitter.emit.bind(this);
this.promise = new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
});
this.then = this.promise.then.bind(this.promise);
}
EventEmitter.prototype.resetHandlers = function () {
for (var i in this.handlers) {
delete this.handlers[i];
}
};
EventEmitter.prototype.on = function (type, handler) {
this.emitter.on(type, handler);
return this;
};
EventEmitter.prototype.once = function (type, handler) {
var _this = this;
this.emitter.on(type, function (e) {
handler(e);
_this.removeEventListener(type);
});
};
EventEmitter.prototype.addEventListener = function (type, handler) {
this.emitter.on(type, handler);
};
EventEmitter.prototype.removeEventListener = function (type, handler) {
if (!type) {
this.handlers = {};
return;
}
if (!handler) {
delete this.handlers[type];
}
else {
return this.emitter.off(type, handler);
}
};
EventEmitter.prototype.onError = function (error) {
this.emitter.on('error', error);
this.removeEventListener('*');
};
EventEmitter.prototype.onData = function (data) {
this.emitter.on('data', data);
this.removeEventListener('*');
};
EventEmitter.prototype.listenerCount = function (listenKey) {
var count = 0;
Object.keys(this.handlers).forEach(function (val) {
if (listenKey === val) {
count += 1;
}
});
return count;
};
return EventEmitter;
}());
export { EventEmitter, GET_TX_ATTEMPTS, HTTPProvider, RPCErrorCode, RPCMethod, Signer, TransactionError, composeMiddleware, isValidResponse, performBatchRPC, performRPC, sign };
//# sourceMappingURL=bundle.js.map
var t,e=function(){};!function(t){t[t.CHECKER_FAILED=0]="CHECKER_FAILED",t[t.RUNNER_FAILED=1]="RUNNER_FAILED",t[t.BALANCE_TRANSFER_FAILED=2]="BALANCE_TRANSFER_FAILED",t[t.EXECUTE_CMD_FAILED=3]="EXECUTE_CMD_FAILED",t[t.EXECUTE_CMD_TIMEOUT=4]="EXECUTE_CMD_TIMEOUT",t[t.NO_GAS_REMAINING_FOUND=5]="NO_GAS_REMAINING_FOUND",t[t.NO_ACCEPTED_FOUND=6]="NO_ACCEPTED_FOUND",t[t.CALL_CONTRACT_FAILED=7]="CALL_CONTRACT_FAILED",t[t.CREATE_CONTRACT_FAILED=8]="CREATE_CONTRACT_FAILED",t[t.JSON_OUTPUT_CORRUPTED=9]="JSON_OUTPUT_CORRUPTED",t[t.CONTRACT_NOT_EXIST=10]="CONTRACT_NOT_EXIST",t[t.STATE_CORRUPTED=11]="STATE_CORRUPTED",t[t.LOG_ENTRY_INSTALL_FAILED=12]="LOG_ENTRY_INSTALL_FAILED",t[t.MESSAGE_CORRUPTED=13]="MESSAGE_CORRUPTED",t[t.RECEIPT_IS_NULL=14]="RECEIPT_IS_NULL",t[t.MAX_DEPTH_REACHED=15]="MAX_DEPTH_REACHED",t[t.CHAIN_CALL_DIFF_SHARD=16]="CHAIN_CALL_DIFF_SHARD",t[t.PREPARATION_FAILED=17]="PREPARATION_FAILED",t[t.NO_OUTPUT=18]="NO_OUTPUT",t[t.OUTPUT_ILLEGAL=19]="OUTPUT_ILLEGAL"}(t||(t={}));var r=function(t,e){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},r(t,e)};var n=function(){return n=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function o(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{u(n.next(t))}catch(t){i(t)}}function a(t){try{u(n.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((n=n.apply(t,e||[])).next())}))}function i(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function s(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,o,i=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function u(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}var c,l,h=function(t,e,r){var n=r.value;return r.value=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return n&&t.bytes?[4,this.signer.sign(t)]:[3,2];case 1:return r=o.sent(),[2,n.call.apply(n,u([this,r],a(e),!1))];case 2:return[2]}}))}))},r};!function(t){if(!t.fetch){var e="URLSearchParams"in t,r="Symbol"in t&&"iterator"in Symbol,n="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),o="FormData"in t,i="ArrayBuffer"in t;if(i)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(t){return t&&DataView.prototype.isPrototypeOf(t)},u=ArrayBuffer.isView||function(t){return t&&s.indexOf(Object.prototype.toString.call(t))>-1};d.prototype.append=function(t,e){t=h(t),e=f(e);var r=this.map[t];this.map[t]=r?r+","+e:e},d.prototype.delete=function(t){delete this.map[h(t)]},d.prototype.get=function(t){return t=h(t),this.has(t)?this.map[t]:null},d.prototype.has=function(t){return this.map.hasOwnProperty(h(t))},d.prototype.set=function(t,e){this.map[h(t)]=f(e)},d.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},d.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),p(t)},d.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),p(t)},d.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),p(t)},r&&(d.prototype[Symbol.iterator]=d.prototype.entries);var c=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];A.prototype.clone=function(){return new A(this,{body:this._bodyInit})},T.call(A.prototype),T.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},m.error=function(){var t=new m(null,{status:0,statusText:""});return t.type="error",t};var l=[301,302,303,307,308];m.redirect=function(t,e){if(-1===l.indexOf(e))throw new RangeError("Invalid status code");return new m(null,{status:e,headers:{location:t}})},t.Headers=d,t.Request=A,t.Response=m,t.fetch=function(t,e){return new Promise((function(r,o){var i=new A(t,e),s=new XMLHttpRequest;s.onload=function(){var t,e,n={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",e=new d,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};n.url="responseURL"in s?s.responseURL:n.headers.get("X-Request-URL");var o="response"in s?s.response:s.responseText;r(new m(o,n))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.open(i.method,i.url,!0),"include"===i.credentials?s.withCredentials=!0:"omit"===i.credentials&&(s.withCredentials=!1),"responseType"in s&&n&&(s.responseType="blob"),i.headers.forEach((function(t,e){s.setRequestHeader(e,t)})),s.send(void 0===i._bodyInit?null:i._bodyInit)}))},t.fetch.polyfill=!0}function h(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function f(t){return"string"!=typeof t&&(t=String(t)),t}function p(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return r&&(e[Symbol.iterator]=function(){return e}),e}function d(t){this.map={},t instanceof d?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function y(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function E(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function _(t){var e=new FileReader,r=E(e);return e.readAsArrayBuffer(t),r}function R(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t,t)if("string"==typeof t)this._bodyText=t;else if(n&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(o&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(i&&n&&a(t))this._bodyArrayBuffer=R(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!i||!ArrayBuffer.prototype.isPrototypeOf(t)&&!u(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=R(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n&&(this.blob=function(){var t=y(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?y(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(_)}),this.text=function(){var t,e,r,n=y(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=E(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}function A(t,e){var r,n,o=(e=e||{}).body;if(t instanceof A){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new d(t.headers)),this.method=t.method,this.mode=t.mode,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new d(e.headers)),this.method=(r=e.method||this.method||"GET",n=r.toUpperCase(),c.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function m(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new d(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:void 0),function(t){t.GetNetworkId="GetNetworkId",t.GetBlockchainInfo="GetBlockchainInfo",t.GetShardingStructure="GetShardingStructure",t.GetDSBlock="GetDsBlock",t.GetLatestDSBlock="GetLatestDsBlock",t.GetNumDSBlocks="GetNumDSBlocks",t.GetDSBlockRate="GetDSBlockRate",t.DSBlockListing="DSBlockListing",t.GetTxBlock="GetTxBlock",t.GetLatestTxBlock="GetLatestTxBlock",t.GetNumTxBlocks="GetNumTxBlocks",t.GetTxBlockRate="GetTxBlockRate",t.TxBlockListing="TxBlockListing",t.GetNumTransactions="GetNumTransactions",t.GetTransactionRate="GetTransactionRate",t.GetCurrentMiniEpoch="GetCurrentMiniEpoch",t.GetCurrentDSEpoch="GetCurrentDSEpoch",t.GetPrevDifficulty="GetPrevDifficulty",t.GetPrevDSDifficulty="GetPrevDSDifficulty",t.GetTotalCoinSupply="GetTotalCoinSupply",t.GetMinerInfo="GetMinerInfo",t.CreateTransaction="CreateTransaction",t.GetTransaction="GetTransaction",t.GetTransactionStatus="GetTransactionStatus",t.GetRecentTransactions="GetRecentTransactions",t.GetTransactionsForTxBlock="GetTransactionsForTxBlock",t.GetTransactionsForTxBlockEx="GetTransactionsForTxBlockEx",t.GetTxnBodiesForTxBlock="GetTxnBodiesForTxBlock",t.GetTxnBodiesForTxBlockEx="GetTxnBodiesForTxBlockEx",t.GetNumTxnsTxEpoch="GetNumTxnsTxEpoch",t.GetNumTxnsDSEpoch="GetNumTxnsDSEpoch",t.GetMinimumGasPrice="GetMinimumGasPrice",t.GetContractAddressFromTransactionID="GetContractAddressFromTransactionID",t.GetSmartContracts="GetSmartContracts",t.GetSmartContractCode="GetSmartContractCode",t.GetSmartContractInit="GetSmartContractInit",t.GetSmartContractState="GetSmartContractState",t.GetSmartContractSubState="GetSmartContractSubState",t.GetStateProof="GetStateProof",t.GetBalance="GetBalance"}(c||(c={})),function(t){t[t.RPC_INVALID_REQUEST=-32600]="RPC_INVALID_REQUEST",t[t.RPC_METHOD_NOT_FOUND=-32601]="RPC_METHOD_NOT_FOUND",t[t.RPC_INVALID_PARAMS=-32602]="RPC_INVALID_PARAMS",t[t.RPC_INTERNAL_ERROR=-32603]="RPC_INTERNAL_ERROR",t[t.RPC_PARSE_ERROR=-32700]="RPC_PARSE_ERROR",t[t.RPC_MISC_ERROR=-1]="RPC_MISC_ERROR",t[t.RPC_TYPE_ERROR=-3]="RPC_TYPE_ERROR",t[t.RPC_INVALID_ADDRESS_OR_KEY=-5]="RPC_INVALID_ADDRESS_OR_KEY",t[t.RPC_INVALID_PARAMETER=-8]="RPC_INVALID_PARAMETER",t[t.RPC_DATABASE_ERROR=-20]="RPC_DATABASE_ERROR",t[t.RPC_DESERIALIZATION_ERROR=-22]="RPC_DESERIALIZATION_ERROR",t[t.RPC_VERIFY_ERROR=-25]="RPC_VERIFY_ERROR",t[t.RPC_VERIFY_REJECTED=-26]="RPC_VERIFY_REJECTED",t[t.RPC_IN_WARMUP=-28]="RPC_IN_WARMUP",t[t.RPC_METHOD_DEPRECATED=-32]="RPC_METHOD_DEPRECATED"}(l||(l={}));var f,p={"Content-Type":"application/json"},d=function(t,e){return o(void 0,void 0,void 0,(function(){return i(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,fetch(t.url,{method:"POST",cache:"no-cache",mode:"cors",redirect:"follow",body:JSON.stringify(t.payload),headers:n(n({},p),t.options&&t.options.headers||{})})];case 1:return[2,r.sent().json().then((function(e){return n(n({},e),{req:t})})).then(e)];case 2:throw r.sent();case 3:return[2]}}))}))},y=function(t,e){return o(void 0,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,fetch(t.url,{method:"POST",cache:"no-cache",mode:"cors",redirect:"follow",referrer:"no-referrer",body:JSON.stringify(t.payload),headers:n(n({},p),t.options&&t.options.headers||{})})];case 1:return[2,e.sent().json().then((function(e){return{batch_result:e,req:t}})).then()];case 2:throw e.sent();case 3:return[2]}}))}))};function E(t){return!("2.0"!==t.jsonrpc||"1"!==t.id&&1!==t.id||!t.error&&!t.result)}function _(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 0===t.length?function(t){return t}:1===t.length?t[0]:t.reduce((function(t,e){return function(r){return t(e(r))}}))}!function(t){t[t.REQ=0]="REQ",t[t.RES=1]="RES"}(f||(f={}));var R=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e.prototype.buildPayload=function(t,e){return{url:this.nodeURL,payload:{id:1,jsonrpc:"2.0",method:t,params:e}}},e.prototype.buildBatchPayload=function(t,e){for(var r=[],n=0;n<e.length;n++){var o=e[n],i=void 0;i=Array.isArray(o)?o:[o],r.push({id:n+1,jsonrpc:"2.0",method:t,params:i})}return{url:this.nodeURL,payload:r}},e.prototype.send=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];var n=a(this.getMiddleware(t),2),o=n[0],i=n[1],s=_.apply(void 0,u([],a(o),!1)),c=_.apply(void 0,u([],a(i),!1)),l=s(this.buildPayload(t,e));return d(l,c)},e.prototype.sendBatch=function(t,e){var r=a(this.getMiddleware(t),2),n=r[0],o=r[1],i=_.apply(void 0,u([],a(n),!1));_.apply(void 0,u([],a(o),!1));var s=i(this.buildBatchPayload(t,e));return y(s)},e.prototype.subscribe=function(t,e){throw new Error("HTTPProvider does not support subscriptions.")},e.prototype.unsubscribe=function(t){throw new Error("HTTPProvider does not support subscriptions.")},e}(function(){function t(t,e,r){void 0===e&&(e=new Map),void 0===r&&(r=new Map);var n=this;this.middleware={request:{use:function(t,e){void 0===e&&(e="*"),n.pushMiddleware(t,0,e)}},response:{use:function(t,e){void 0===e&&(e="*"),n.pushMiddleware(t,1,e)}}},this.nodeURL=t,this.reqMiddleware=e,this.resMiddleware=r}return t.prototype.pushMiddleware=function(t,e,r){if(0!==e&&1!==e)throw new Error("Please specify the type of middleware being added");if(0===e){var n=this.reqMiddleware.get(r)||[];this.reqMiddleware.set(r,u(u([],a(n),!1),[t],!1))}else{n=this.resMiddleware.get(r)||[];this.resMiddleware.set(r,u(u([],a(n),!1),[t],!1))}},t.prototype.getMiddleware=function(t){var e,r,n,o,i=[],c=[];try{for(var l=s(this.reqMiddleware.entries()),h=l.next();!h.done;h=l.next()){var f=a(h.value,2),p=f[0],d=f[1];"string"==typeof p&&"*"!==p&&p===t&&i.push.apply(i,u([],a(d),!1)),p instanceof RegExp&&p.test(t)&&i.push.apply(i,u([],a(d),!1)),"*"===p&&i.push.apply(i,u([],a(d),!1))}}catch(t){e={error:t}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var y=s(this.resMiddleware.entries()),E=y.next();!E.done;E=y.next()){var _=a(E.value,2);p=_[0],d=_[1];"string"==typeof p&&"*"!==p&&p===t&&c.push.apply(c,u([],a(d),!1)),p instanceof RegExp&&p.test(t)&&c.push.apply(c,u([],a(d),!1)),"*"===p&&c.push.apply(c,u([],a(d),!1))}}catch(t){n={error:t}}finally{try{E&&!E.done&&(o=y.return)&&o.call(y)}finally{if(n)throw n.error}}return[i,c]},t}()),T=33;function A(t){return t=t||Object.create(null),{on:function(e,r){(t[e]||(t[e]=[])).push(r)},off:function(e,r){t[e]&&t[e].splice(t[e].indexOf(r)>>>0,1)},emit:function(e,r){(t[e]||[]).slice().map((function(t){t(r)})),(t["*"]||[]).slice().map((function(t){t(e,r)}))}}}var b=function(){function t(){var t=this;this.handlers={},this.emitter=new A(this.handlers),this.off=this.emitter.off.bind(this),this.emit=this.emitter.emit.bind(this),this.promise=new Promise((function(e,r){t.resolve=e,t.reject=r})),this.then=this.promise.then.bind(this.promise)}return t.prototype.resetHandlers=function(){for(var t in this.handlers)delete this.handlers[t]},t.prototype.on=function(t,e){return this.emitter.on(t,e),this},t.prototype.once=function(t,e){var r=this;this.emitter.on(t,(function(n){e(n),r.removeEventListener(t)}))},t.prototype.addEventListener=function(t,e){this.emitter.on(t,e)},t.prototype.removeEventListener=function(t,e){if(t)return e?this.emitter.off(t,e):void delete this.handlers[t];this.handlers={}},t.prototype.onError=function(t){this.emitter.on("error",t),this.removeEventListener("*")},t.prototype.onData=function(t){this.emitter.on("data",t),this.removeEventListener("*")},t.prototype.listenerCount=function(t){var e=0;return Object.keys(this.handlers).forEach((function(r){t===r&&(e+=1)})),e},t}();export{b as EventEmitter,T as GET_TX_ATTEMPTS,R as HTTPProvider,l as RPCErrorCode,c as RPCMethod,e as Signer,t as TransactionError,_ as composeMiddleware,E as isValidResponse,y as performBatchRPC,d as performRPC,h as sign};

@@ -1,1209 +0,1 @@

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@zilliqa-js/core"] = {}));
})(this, (function (exports) { 'use strict';
// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
var Signer = /** @class */ (function () {
function Signer() {
}
return Signer;
}());
exports.TransactionError = void 0;
(function (TransactionError) {
TransactionError[TransactionError["CHECKER_FAILED"] = 0] = "CHECKER_FAILED";
TransactionError[TransactionError["RUNNER_FAILED"] = 1] = "RUNNER_FAILED";
TransactionError[TransactionError["BALANCE_TRANSFER_FAILED"] = 2] = "BALANCE_TRANSFER_FAILED";
TransactionError[TransactionError["EXECUTE_CMD_FAILED"] = 3] = "EXECUTE_CMD_FAILED";
TransactionError[TransactionError["EXECUTE_CMD_TIMEOUT"] = 4] = "EXECUTE_CMD_TIMEOUT";
TransactionError[TransactionError["NO_GAS_REMAINING_FOUND"] = 5] = "NO_GAS_REMAINING_FOUND";
TransactionError[TransactionError["NO_ACCEPTED_FOUND"] = 6] = "NO_ACCEPTED_FOUND";
TransactionError[TransactionError["CALL_CONTRACT_FAILED"] = 7] = "CALL_CONTRACT_FAILED";
TransactionError[TransactionError["CREATE_CONTRACT_FAILED"] = 8] = "CREATE_CONTRACT_FAILED";
TransactionError[TransactionError["JSON_OUTPUT_CORRUPTED"] = 9] = "JSON_OUTPUT_CORRUPTED";
TransactionError[TransactionError["CONTRACT_NOT_EXIST"] = 10] = "CONTRACT_NOT_EXIST";
TransactionError[TransactionError["STATE_CORRUPTED"] = 11] = "STATE_CORRUPTED";
TransactionError[TransactionError["LOG_ENTRY_INSTALL_FAILED"] = 12] = "LOG_ENTRY_INSTALL_FAILED";
TransactionError[TransactionError["MESSAGE_CORRUPTED"] = 13] = "MESSAGE_CORRUPTED";
TransactionError[TransactionError["RECEIPT_IS_NULL"] = 14] = "RECEIPT_IS_NULL";
TransactionError[TransactionError["MAX_DEPTH_REACHED"] = 15] = "MAX_DEPTH_REACHED";
TransactionError[TransactionError["CHAIN_CALL_DIFF_SHARD"] = 16] = "CHAIN_CALL_DIFF_SHARD";
TransactionError[TransactionError["PREPARATION_FAILED"] = 17] = "PREPARATION_FAILED";
TransactionError[TransactionError["NO_OUTPUT"] = 18] = "NO_OUTPUT";
TransactionError[TransactionError["OUTPUT_ILLEGAL"] = 19] = "OUTPUT_ILLEGAL";
})(exports.TransactionError || (exports.TransactionError = {}));
/******************************************************************************
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) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
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 __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 (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 };
}
}
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 __spreadArray(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));
}
// Copyright (C) 2018 Zilliqa
/**
* sign
*
* This decorates a method by attempting to sign the first argument of the
* intercepted method.
*
* @param {T} target
* @param {K} key
* @param {PropertyDescriptor} descriptor
* @returns {PropertyDescriptor | undefined}
*/
var sign = function (target, key, descriptor) {
var original = descriptor.value;
function interceptor(arg) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function () {
var signed;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(original && arg.bytes)) return [3 /*break*/, 2];
return [4 /*yield*/, this.signer.sign(arg)];
case 1:
signed = _a.sent();
return [2 /*return*/, original.call.apply(original, __spreadArray([this, signed], __read(args), false))];
case 2: return [2 /*return*/];
}
});
});
}
descriptor.value = interceptor;
return descriptor;
};
(function(self) {
if (self.fetch) {
return
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob();
return true
} catch(e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isDataView = function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
};
var isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {done: value === undefined, value: value}
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
};
}
return iterator
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue+','+value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) { items.push(name); });
return iteratorFor(items)
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) { items.push(value); });
return iteratorFor(items)
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) { items.push([name, value]); });
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
throw new Error('unsupported BodyInit type')
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
};
}
this.json = function() {
return this.text().then(JSON.parse)
};
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return (methods.indexOf(upcased) > -1) ? upcased : method
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'omit';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit })
};
function decode(body) {
var form = new FormData();
body.trim().split('&').forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = 'statusText' in options ? options.statusText : 'OK';
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
};
self.Headers = Headers;
self.Request = Request;
self.Response = Response;
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
};
self.fetch.polyfill = true;
})(typeof self !== 'undefined' ? self : undefined);
/**
* blockchain-side.
*/
exports.RPCMethod = void 0;
(function (RPCMethod) {
// Network-related methods
RPCMethod["GetNetworkId"] = "GetNetworkId";
// Blockchain-related methods
RPCMethod["GetBlockchainInfo"] = "GetBlockchainInfo";
RPCMethod["GetShardingStructure"] = "GetShardingStructure";
RPCMethod["GetDSBlock"] = "GetDsBlock";
RPCMethod["GetLatestDSBlock"] = "GetLatestDsBlock";
RPCMethod["GetNumDSBlocks"] = "GetNumDSBlocks";
RPCMethod["GetDSBlockRate"] = "GetDSBlockRate";
RPCMethod["DSBlockListing"] = "DSBlockListing";
RPCMethod["GetTxBlock"] = "GetTxBlock";
RPCMethod["GetLatestTxBlock"] = "GetLatestTxBlock";
RPCMethod["GetNumTxBlocks"] = "GetNumTxBlocks";
RPCMethod["GetTxBlockRate"] = "GetTxBlockRate";
RPCMethod["TxBlockListing"] = "TxBlockListing";
RPCMethod["GetNumTransactions"] = "GetNumTransactions";
RPCMethod["GetTransactionRate"] = "GetTransactionRate";
RPCMethod["GetCurrentMiniEpoch"] = "GetCurrentMiniEpoch";
RPCMethod["GetCurrentDSEpoch"] = "GetCurrentDSEpoch";
RPCMethod["GetPrevDifficulty"] = "GetPrevDifficulty";
RPCMethod["GetPrevDSDifficulty"] = "GetPrevDSDifficulty";
RPCMethod["GetTotalCoinSupply"] = "GetTotalCoinSupply";
RPCMethod["GetMinerInfo"] = "GetMinerInfo";
// Transaction-related methods
RPCMethod["CreateTransaction"] = "CreateTransaction";
RPCMethod["GetTransaction"] = "GetTransaction";
RPCMethod["GetTransactionStatus"] = "GetTransactionStatus";
RPCMethod["GetRecentTransactions"] = "GetRecentTransactions";
RPCMethod["GetTransactionsForTxBlock"] = "GetTransactionsForTxBlock";
RPCMethod["GetTransactionsForTxBlockEx"] = "GetTransactionsForTxBlockEx";
RPCMethod["GetTxnBodiesForTxBlock"] = "GetTxnBodiesForTxBlock";
RPCMethod["GetTxnBodiesForTxBlockEx"] = "GetTxnBodiesForTxBlockEx";
RPCMethod["GetNumTxnsTxEpoch"] = "GetNumTxnsTxEpoch";
RPCMethod["GetNumTxnsDSEpoch"] = "GetNumTxnsDSEpoch";
RPCMethod["GetMinimumGasPrice"] = "GetMinimumGasPrice";
// Contract-related methods
RPCMethod["GetContractAddressFromTransactionID"] = "GetContractAddressFromTransactionID";
RPCMethod["GetSmartContracts"] = "GetSmartContracts";
RPCMethod["GetSmartContractCode"] = "GetSmartContractCode";
RPCMethod["GetSmartContractInit"] = "GetSmartContractInit";
RPCMethod["GetSmartContractState"] = "GetSmartContractState";
RPCMethod["GetSmartContractSubState"] = "GetSmartContractSubState";
RPCMethod["GetStateProof"] = "GetStateProof";
// Account-related methods
RPCMethod["GetBalance"] = "GetBalance";
})(exports.RPCMethod || (exports.RPCMethod = {}));
exports.RPCErrorCode = void 0;
(function (RPCErrorCode) {
// Standard JSON-RPC 2.0 errors
// RPC_INVALID_REQUEST is internally mapped to HTTP_BAD_REQUEST (400).
// It should not be used for application-layer errors.
RPCErrorCode[RPCErrorCode["RPC_INVALID_REQUEST"] = -32600] = "RPC_INVALID_REQUEST";
// RPC_METHOD_NOT_FOUND is internally mapped to HTTP_NOT_FOUND (404).
// It should not be used for application-layer errors.
RPCErrorCode[RPCErrorCode["RPC_METHOD_NOT_FOUND"] = -32601] = "RPC_METHOD_NOT_FOUND";
RPCErrorCode[RPCErrorCode["RPC_INVALID_PARAMS"] = -32602] = "RPC_INVALID_PARAMS";
// RPC_INTERNAL_ERROR should only be used for genuine errors in bitcoind
// (for example datadir corruption).
RPCErrorCode[RPCErrorCode["RPC_INTERNAL_ERROR"] = -32603] = "RPC_INTERNAL_ERROR";
RPCErrorCode[RPCErrorCode["RPC_PARSE_ERROR"] = -32700] = "RPC_PARSE_ERROR";
// General application defined errors
RPCErrorCode[RPCErrorCode["RPC_MISC_ERROR"] = -1] = "RPC_MISC_ERROR";
RPCErrorCode[RPCErrorCode["RPC_TYPE_ERROR"] = -3] = "RPC_TYPE_ERROR";
RPCErrorCode[RPCErrorCode["RPC_INVALID_ADDRESS_OR_KEY"] = -5] = "RPC_INVALID_ADDRESS_OR_KEY";
RPCErrorCode[RPCErrorCode["RPC_INVALID_PARAMETER"] = -8] = "RPC_INVALID_PARAMETER";
RPCErrorCode[RPCErrorCode["RPC_DATABASE_ERROR"] = -20] = "RPC_DATABASE_ERROR";
RPCErrorCode[RPCErrorCode["RPC_DESERIALIZATION_ERROR"] = -22] = "RPC_DESERIALIZATION_ERROR";
RPCErrorCode[RPCErrorCode["RPC_VERIFY_ERROR"] = -25] = "RPC_VERIFY_ERROR";
RPCErrorCode[RPCErrorCode["RPC_VERIFY_REJECTED"] = -26] = "RPC_VERIFY_REJECTED";
RPCErrorCode[RPCErrorCode["RPC_IN_WARMUP"] = -28] = "RPC_IN_WARMUP";
RPCErrorCode[RPCErrorCode["RPC_METHOD_DEPRECATED"] = -32] = "RPC_METHOD_DEPRECATED";
})(exports.RPCErrorCode || (exports.RPCErrorCode = {}));
var DEFAULT_HEADERS = { "Content-Type": "application/json" };
var performRPC = function (request, handler) { return __awaiter(void 0, void 0, void 0, function () {
var response, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, fetch(request.url, {
method: "POST",
cache: "no-cache",
mode: "cors",
redirect: "follow",
body: JSON.stringify(request.payload),
headers: __assign(__assign({}, DEFAULT_HEADERS), ((request.options && request.options.headers) || {})),
})];
case 1:
response = _a.sent();
return [2 /*return*/, response
.json()
.then(function (body) {
return __assign(__assign({}, body), { req: request });
})
.then(handler)];
case 2:
err_1 = _a.sent();
throw err_1;
case 3: return [2 /*return*/];
}
});
}); };
// identical to performRPC; difference is the response
var performBatchRPC = function (request, handler // eslint-disable-line @typescript-eslint/no-unused-vars
) { return __awaiter(void 0, void 0, void 0, function () {
var response, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, fetch(request.url, {
method: "POST",
cache: "no-cache",
mode: "cors",
redirect: "follow",
referrer: "no-referrer",
body: JSON.stringify(request.payload),
headers: __assign(__assign({}, DEFAULT_HEADERS), ((request.options && request.options.headers) || {})),
})];
case 1:
response = _a.sent();
return [2 /*return*/, (response
.json()
.then(function (batch_result) {
return { batch_result: batch_result, req: request };
})
// no handler as compared to performRPC to preserve the body array
// e.g. response
/*
{ body:
[ { id: 1, jsonrpc: '2.0', result: [Object] },
{ id: 1, jsonrpc: '2.0', result: [Object] } ],
req:
{ url: 'https://dev-api.zilliqa.com',
payload: [ [Object], [Object] ] } }
*/
.then())];
case 2:
err_2 = _a.sent();
throw err_2;
case 3: return [2 /*return*/];
}
});
}); };
// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
function isValidResponse(response) {
if (response.jsonrpc === '2.0' &&
(response.id === '1' || response.id === 1) &&
(response.error || response.result)) {
return true;
}
return false;
}
function composeMiddleware() {
var fns = [];
for (var _i = 0; _i < arguments.length; _i++) {
fns[_i] = arguments[_i];
}
if (fns.length === 0) {
return function (arg) { return arg; };
}
if (fns.length === 1) {
return fns[0];
}
return fns.reduce(function (a, b) { return function (arg) { return a(b(arg)); }; });
}
// Copyright (C) 2018 Zilliqa
var MiddlewareType;
(function (MiddlewareType) {
MiddlewareType[MiddlewareType["REQ"] = 0] = "REQ";
MiddlewareType[MiddlewareType["RES"] = 1] = "RES";
})(MiddlewareType || (MiddlewareType = {}));
var BaseProvider = /** @class */ (function () {
function BaseProvider(nodeURL, reqMiddleware, resMiddleware) {
if (reqMiddleware === void 0) { reqMiddleware = new Map(); }
if (resMiddleware === void 0) { resMiddleware = new Map(); }
var _this = this;
this.middleware = {
request: {
use: function (fn, match) {
if (match === void 0) { match = '*'; }
_this.pushMiddleware(fn, 0 /* MiddlewareType.REQ */, match);
},
},
response: {
use: function (fn, match) {
if (match === void 0) { match = '*'; }
_this.pushMiddleware(fn, 1 /* MiddlewareType.RES */, match);
},
},
};
this.nodeURL = nodeURL;
this.reqMiddleware = reqMiddleware;
this.resMiddleware = resMiddleware;
}
/**
* pushMiddleware
*
* Adds the middleware to the appropriate middleware map.
*
* @param {ResMiddlewareFn}
* @param {T} type
* @param {Matcher} match
* @returns {void}
*/
BaseProvider.prototype.pushMiddleware = function (fn, type, match) {
if (type !== 0 /* MiddlewareType.REQ */ && type !== 1 /* MiddlewareType.RES */) {
throw new Error('Please specify the type of middleware being added');
}
if (type === 0 /* MiddlewareType.REQ */) {
var current = this.reqMiddleware.get(match) || [];
this.reqMiddleware.set(match, __spreadArray(__spreadArray([], __read(current), false), [fn], false));
}
else {
var current = this.resMiddleware.get(match) || [];
this.resMiddleware.set(match, __spreadArray(__spreadArray([], __read(current), false), [fn], false));
}
};
/**
* getMiddleware
*
* Returns the middleware that matches the matcher provided. Note that
* middleware are called in order of specificity: string -> regexp ->
* wildcard.
*
* @param {Matcher} match
* @returns {[ReqMiddlewareFn[], ResMiddlewareFn[]]}
*/
BaseProvider.prototype.getMiddleware = function (method) {
var e_1, _a, e_2, _b;
var reqFns = [];
var resFns = [];
try {
for (var _c = __values(this.reqMiddleware.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), key = _e[0], transformers = _e[1];
if (typeof key === 'string' && key !== '*' && key === method) {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
if (key instanceof RegExp && key.test(method)) {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
if (key === '*') {
reqFns.push.apply(reqFns, __spreadArray([], __read(transformers), false));
}
}
}
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; }
}
try {
for (var _f = __values(this.resMiddleware.entries()), _g = _f.next(); !_g.done; _g = _f.next()) {
var _h = __read(_g.value, 2), key = _h[0], transformers = _h[1];
if (typeof key === 'string' && key !== '*' && key === method) {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
if (key instanceof RegExp && key.test(method)) {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
if (key === '*') {
resFns.push.apply(resFns, __spreadArray([], __read(transformers), false));
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
return [reqFns, resFns];
};
return BaseProvider;
}());
// Copyright (C) 2018 Zilliqa
var HTTPProvider = /** @class */ (function (_super) {
__extends(HTTPProvider, _super);
function HTTPProvider() {
return _super !== null && _super.apply(this, arguments) || this;
}
HTTPProvider.prototype.buildPayload = function (method, params) {
return {
url: this.nodeURL,
payload: { id: 1, jsonrpc: '2.0', method: method, params: params },
};
};
HTTPProvider.prototype.buildBatchPayload = function (method, paramsList) {
var payloads = [];
for (var i = 0; i < paramsList.length; i++) {
// most of the payloads should be a single param, e.g. GetTransaction
// however, there are special cases e.g. GetSmartContractSubState & GetTransactionsForTxBlockEx
// where the param field is a list
var payloadParams = paramsList[i];
var params = void 0;
if (Array.isArray(payloadParams)) {
// for those param field that is already a list
params = payloadParams;
}
else {
params = [payloadParams];
}
// id start from index 1
payloads.push({
id: i + 1,
jsonrpc: '2.0',
method: method,
params: params,
});
}
return {
url: this.nodeURL,
payload: payloads,
};
};
HTTPProvider.prototype.send = function (method) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
var _a = __read(this.getMiddleware(method), 2), tReq = _a[0], tRes = _a[1];
var reqMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tReq), false));
var resMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tRes), false));
var req = reqMiddleware(this.buildPayload(method, params));
return performRPC(req, resMiddleware);
};
HTTPProvider.prototype.sendBatch = function (method, params) {
var _a = __read(this.getMiddleware(method), 2), tReq = _a[0], tRes = _a[1];
var reqMiddleware = composeMiddleware.apply(void 0, __spreadArray([], __read(tReq), false));
composeMiddleware.apply(void 0, __spreadArray([], __read(tRes), false));
var batchPayload = this.buildBatchPayload(method, params);
var req = reqMiddleware(batchPayload);
return performBatchRPC(req);
};
HTTPProvider.prototype.subscribe = function (event, subscriber) {
throw new Error('HTTPProvider does not support subscriptions.');
};
HTTPProvider.prototype.unsubscribe = function (token) {
throw new Error('HTTPProvider does not support subscriptions.');
};
return HTTPProvider;
}(BaseProvider));
// Copyright (C) 2018 Zilliqa
//
// This file is part of zilliqa-js
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// this constant is used to indicate the number of times to poll the
// blockchain for a transaction confirmation. this number has been selected by
// using a heuristic to calculate the approximate maximum amount of time it
// should take for a transaction to be confirmed, even during a PoW submission
// round.
var GET_TX_ATTEMPTS = 33;
//
// An event handler can take an optional event argument
// and should not return a value
// An array of all currently registered event handlers for a type
// A map of event types and their corresponding event handlers.
/** Mitt: Tiny (~200b) functional event emitter / pubsub.
* @name mitt
* @returns {Mitt}
*/
function mitt(all ) {
all = all || Object.create(null);
return {
/**
* Register an event handler for the given type.
*
* @param {String} type Type of event to listen for, or `"*"` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
on: function on(type , handler ) {
(all[type] || (all[type] = [])).push(handler);
},
/**
* Remove an event handler for the given type.
*
* @param {String} type Type of event to unregister `handler` from, or `"*"`
* @param {Function} handler Handler function to remove
* @memberOf mitt
*/
off: function off(type , handler ) {
if (all[type]) {
all[type].splice(all[type].indexOf(handler) >>> 0, 1);
}
},
/**
* Invoke all handlers for the given type.
* If present, `"*"` handlers are invoked after type-matched handlers.
*
* @param {String} type The event type to invoke
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
* @memberOf mitt
*/
emit: function emit(type , evt ) {
(all[type] || []).slice().map(function (handler) { handler(evt); });
(all['*'] || []).slice().map(function (handler) { handler(type, evt); });
}
};
}
// Copyright (C) 2018 Zilliqa
var EventEmitter = /** @class */ (function () {
function EventEmitter() {
var _this = this;
this.handlers = {};
// TODO: As any added to solve
// error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
this.emitter = new mitt(this.handlers);
this.off = this.emitter.off.bind(this);
this.emit = this.emitter.emit.bind(this);
this.promise = new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
});
this.then = this.promise.then.bind(this.promise);
}
EventEmitter.prototype.resetHandlers = function () {
for (var i in this.handlers) {
delete this.handlers[i];
}
};
EventEmitter.prototype.on = function (type, handler) {
this.emitter.on(type, handler);
return this;
};
EventEmitter.prototype.once = function (type, handler) {
var _this = this;
this.emitter.on(type, function (e) {
handler(e);
_this.removeEventListener(type);
});
};
EventEmitter.prototype.addEventListener = function (type, handler) {
this.emitter.on(type, handler);
};
EventEmitter.prototype.removeEventListener = function (type, handler) {
if (!type) {
this.handlers = {};
return;
}
if (!handler) {
delete this.handlers[type];
}
else {
return this.emitter.off(type, handler);
}
};
EventEmitter.prototype.onError = function (error) {
this.emitter.on('error', error);
this.removeEventListener('*');
};
EventEmitter.prototype.onData = function (data) {
this.emitter.on('data', data);
this.removeEventListener('*');
};
EventEmitter.prototype.listenerCount = function (listenKey) {
var count = 0;
Object.keys(this.handlers).forEach(function (val) {
if (listenKey === val) {
count += 1;
}
});
return count;
};
return EventEmitter;
}());
exports.EventEmitter = EventEmitter;
exports.GET_TX_ATTEMPTS = GET_TX_ATTEMPTS;
exports.HTTPProvider = HTTPProvider;
exports.Signer = Signer;
exports.composeMiddleware = composeMiddleware;
exports.isValidResponse = isValidResponse;
exports.performBatchRPC = performBatchRPC;
exports.performRPC = performRPC;
exports.sign = sign;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=bundle.js.map
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["@zilliqa-js/core"]={})}(this,(function(t){"use strict";var e,r=function(){};t.TransactionError=void 0,(e=t.TransactionError||(t.TransactionError={}))[e.CHECKER_FAILED=0]="CHECKER_FAILED",e[e.RUNNER_FAILED=1]="RUNNER_FAILED",e[e.BALANCE_TRANSFER_FAILED=2]="BALANCE_TRANSFER_FAILED",e[e.EXECUTE_CMD_FAILED=3]="EXECUTE_CMD_FAILED",e[e.EXECUTE_CMD_TIMEOUT=4]="EXECUTE_CMD_TIMEOUT",e[e.NO_GAS_REMAINING_FOUND=5]="NO_GAS_REMAINING_FOUND",e[e.NO_ACCEPTED_FOUND=6]="NO_ACCEPTED_FOUND",e[e.CALL_CONTRACT_FAILED=7]="CALL_CONTRACT_FAILED",e[e.CREATE_CONTRACT_FAILED=8]="CREATE_CONTRACT_FAILED",e[e.JSON_OUTPUT_CORRUPTED=9]="JSON_OUTPUT_CORRUPTED",e[e.CONTRACT_NOT_EXIST=10]="CONTRACT_NOT_EXIST",e[e.STATE_CORRUPTED=11]="STATE_CORRUPTED",e[e.LOG_ENTRY_INSTALL_FAILED=12]="LOG_ENTRY_INSTALL_FAILED",e[e.MESSAGE_CORRUPTED=13]="MESSAGE_CORRUPTED",e[e.RECEIPT_IS_NULL=14]="RECEIPT_IS_NULL",e[e.MAX_DEPTH_REACHED=15]="MAX_DEPTH_REACHED",e[e.CHAIN_CALL_DIFF_SHARD=16]="CHAIN_CALL_DIFF_SHARD",e[e.PREPARATION_FAILED=17]="PREPARATION_FAILED",e[e.NO_OUTPUT=18]="NO_OUTPUT",e[e.OUTPUT_ILLEGAL=19]="OUTPUT_ILLEGAL";var n=function(t,e){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},n(t,e)};var o=function(){return o=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},o.apply(this,arguments)};function i(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{u(n.next(t))}catch(t){i(t)}}function a(t){try{u(n.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((n=n.apply(t,e||[])).next())}))}function s(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function a(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,o,i=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function c(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}var l,f;!function(t){if(!t.fetch){var e="URLSearchParams"in t,r="Symbol"in t&&"iterator"in Symbol,n="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),o="FormData"in t,i="ArrayBuffer"in t;if(i)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(t){return t&&DataView.prototype.isPrototypeOf(t)},u=ArrayBuffer.isView||function(t){return t&&s.indexOf(Object.prototype.toString.call(t))>-1};p.prototype.append=function(t,e){t=f(t),e=h(e);var r=this.map[t];this.map[t]=r?r+","+e:e},p.prototype.delete=function(t){delete this.map[f(t)]},p.prototype.get=function(t){return t=f(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(f(t))},p.prototype.set=function(t,e){this.map[f(t)]=h(e)},p.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},p.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),d(t)},p.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),d(t)},p.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),d(t)},r&&(p.prototype[Symbol.iterator]=p.prototype.entries);var c=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];A.prototype.clone=function(){return new A(this,{body:this._bodyInit})},T.call(A.prototype),T.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},m.error=function(){var t=new m(null,{status:0,statusText:""});return t.type="error",t};var l=[301,302,303,307,308];m.redirect=function(t,e){if(-1===l.indexOf(e))throw new RangeError("Invalid status code");return new m(null,{status:e,headers:{location:t}})},t.Headers=p,t.Request=A,t.Response=m,t.fetch=function(t,e){return new Promise((function(r,o){var i=new A(t,e),s=new XMLHttpRequest;s.onload=function(){var t,e,n={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",e=new p,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};n.url="responseURL"in s?s.responseURL:n.headers.get("X-Request-URL");var o="response"in s?s.response:s.responseText;r(new m(o,n))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.open(i.method,i.url,!0),"include"===i.credentials?s.withCredentials=!0:"omit"===i.credentials&&(s.withCredentials=!1),"responseType"in s&&n&&(s.responseType="blob"),i.headers.forEach((function(t,e){s.setRequestHeader(e,t)})),s.send(void 0===i._bodyInit?null:i._bodyInit)}))},t.fetch.polyfill=!0}function f(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function h(t){return"string"!=typeof t&&(t=String(t)),t}function d(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return r&&(e[Symbol.iterator]=function(){return e}),e}function p(t){this.map={},t instanceof p?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function y(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function E(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function R(t){var e=new FileReader,r=E(e);return e.readAsArrayBuffer(t),r}function _(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t,t)if("string"==typeof t)this._bodyText=t;else if(n&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(o&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(i&&n&&a(t))this._bodyArrayBuffer=_(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!i||!ArrayBuffer.prototype.isPrototypeOf(t)&&!u(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=_(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n&&(this.blob=function(){var t=y(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?y(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(R)}),this.text=function(){var t,e,r,n=y(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=E(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}function A(t,e){var r,n,o=(e=e||{}).body;if(t instanceof A){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new p(e.headers)),this.method=(r=e.method||this.method||"GET",n=r.toUpperCase(),c.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function m(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new p(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:void 0),t.RPCMethod=void 0,(l=t.RPCMethod||(t.RPCMethod={})).GetNetworkId="GetNetworkId",l.GetBlockchainInfo="GetBlockchainInfo",l.GetShardingStructure="GetShardingStructure",l.GetDSBlock="GetDsBlock",l.GetLatestDSBlock="GetLatestDsBlock",l.GetNumDSBlocks="GetNumDSBlocks",l.GetDSBlockRate="GetDSBlockRate",l.DSBlockListing="DSBlockListing",l.GetTxBlock="GetTxBlock",l.GetLatestTxBlock="GetLatestTxBlock",l.GetNumTxBlocks="GetNumTxBlocks",l.GetTxBlockRate="GetTxBlockRate",l.TxBlockListing="TxBlockListing",l.GetNumTransactions="GetNumTransactions",l.GetTransactionRate="GetTransactionRate",l.GetCurrentMiniEpoch="GetCurrentMiniEpoch",l.GetCurrentDSEpoch="GetCurrentDSEpoch",l.GetPrevDifficulty="GetPrevDifficulty",l.GetPrevDSDifficulty="GetPrevDSDifficulty",l.GetTotalCoinSupply="GetTotalCoinSupply",l.GetMinerInfo="GetMinerInfo",l.CreateTransaction="CreateTransaction",l.GetTransaction="GetTransaction",l.GetTransactionStatus="GetTransactionStatus",l.GetRecentTransactions="GetRecentTransactions",l.GetTransactionsForTxBlock="GetTransactionsForTxBlock",l.GetTransactionsForTxBlockEx="GetTransactionsForTxBlockEx",l.GetTxnBodiesForTxBlock="GetTxnBodiesForTxBlock",l.GetTxnBodiesForTxBlockEx="GetTxnBodiesForTxBlockEx",l.GetNumTxnsTxEpoch="GetNumTxnsTxEpoch",l.GetNumTxnsDSEpoch="GetNumTxnsDSEpoch",l.GetMinimumGasPrice="GetMinimumGasPrice",l.GetContractAddressFromTransactionID="GetContractAddressFromTransactionID",l.GetSmartContracts="GetSmartContracts",l.GetSmartContractCode="GetSmartContractCode",l.GetSmartContractInit="GetSmartContractInit",l.GetSmartContractState="GetSmartContractState",l.GetSmartContractSubState="GetSmartContractSubState",l.GetStateProof="GetStateProof",l.GetBalance="GetBalance",t.RPCErrorCode=void 0,(f=t.RPCErrorCode||(t.RPCErrorCode={}))[f.RPC_INVALID_REQUEST=-32600]="RPC_INVALID_REQUEST",f[f.RPC_METHOD_NOT_FOUND=-32601]="RPC_METHOD_NOT_FOUND",f[f.RPC_INVALID_PARAMS=-32602]="RPC_INVALID_PARAMS",f[f.RPC_INTERNAL_ERROR=-32603]="RPC_INTERNAL_ERROR",f[f.RPC_PARSE_ERROR=-32700]="RPC_PARSE_ERROR",f[f.RPC_MISC_ERROR=-1]="RPC_MISC_ERROR",f[f.RPC_TYPE_ERROR=-3]="RPC_TYPE_ERROR",f[f.RPC_INVALID_ADDRESS_OR_KEY=-5]="RPC_INVALID_ADDRESS_OR_KEY",f[f.RPC_INVALID_PARAMETER=-8]="RPC_INVALID_PARAMETER",f[f.RPC_DATABASE_ERROR=-20]="RPC_DATABASE_ERROR",f[f.RPC_DESERIALIZATION_ERROR=-22]="RPC_DESERIALIZATION_ERROR",f[f.RPC_VERIFY_ERROR=-25]="RPC_VERIFY_ERROR",f[f.RPC_VERIFY_REJECTED=-26]="RPC_VERIFY_REJECTED",f[f.RPC_IN_WARMUP=-28]="RPC_IN_WARMUP",f[f.RPC_METHOD_DEPRECATED=-32]="RPC_METHOD_DEPRECATED";var h,d={"Content-Type":"application/json"},p=function(t,e){return i(void 0,void 0,void 0,(function(){return s(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,fetch(t.url,{method:"POST",cache:"no-cache",mode:"cors",redirect:"follow",body:JSON.stringify(t.payload),headers:o(o({},d),t.options&&t.options.headers||{})})];case 1:return[2,r.sent().json().then((function(e){return o(o({},e),{req:t})})).then(e)];case 2:throw r.sent();case 3:return[2]}}))}))},y=function(t,e){return i(void 0,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,fetch(t.url,{method:"POST",cache:"no-cache",mode:"cors",redirect:"follow",referrer:"no-referrer",body:JSON.stringify(t.payload),headers:o(o({},d),t.options&&t.options.headers||{})})];case 1:return[2,e.sent().json().then((function(e){return{batch_result:e,req:t}})).then()];case 2:throw e.sent();case 3:return[2]}}))}))};function E(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 0===t.length?function(t){return t}:1===t.length?t[0]:t.reduce((function(t,e){return function(r){return t(e(r))}}))}!function(t){t[t.REQ=0]="REQ",t[t.RES=1]="RES"}(h||(h={}));var R=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(e,t),e.prototype.buildPayload=function(t,e){return{url:this.nodeURL,payload:{id:1,jsonrpc:"2.0",method:t,params:e}}},e.prototype.buildBatchPayload=function(t,e){for(var r=[],n=0;n<e.length;n++){var o=e[n],i=void 0;i=Array.isArray(o)?o:[o],r.push({id:n+1,jsonrpc:"2.0",method:t,params:i})}return{url:this.nodeURL,payload:r}},e.prototype.send=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];var n=u(this.getMiddleware(t),2),o=n[0],i=n[1],s=E.apply(void 0,c([],u(o),!1)),a=E.apply(void 0,c([],u(i),!1)),l=s(this.buildPayload(t,e));return p(l,a)},e.prototype.sendBatch=function(t,e){var r=u(this.getMiddleware(t),2),n=r[0],o=r[1],i=E.apply(void 0,c([],u(n),!1));E.apply(void 0,c([],u(o),!1));var s=i(this.buildBatchPayload(t,e));return y(s)},e.prototype.subscribe=function(t,e){throw new Error("HTTPProvider does not support subscriptions.")},e.prototype.unsubscribe=function(t){throw new Error("HTTPProvider does not support subscriptions.")},e}(function(){function t(t,e,r){void 0===e&&(e=new Map),void 0===r&&(r=new Map);var n=this;this.middleware={request:{use:function(t,e){void 0===e&&(e="*"),n.pushMiddleware(t,0,e)}},response:{use:function(t,e){void 0===e&&(e="*"),n.pushMiddleware(t,1,e)}}},this.nodeURL=t,this.reqMiddleware=e,this.resMiddleware=r}return t.prototype.pushMiddleware=function(t,e,r){if(0!==e&&1!==e)throw new Error("Please specify the type of middleware being added");if(0===e){var n=this.reqMiddleware.get(r)||[];this.reqMiddleware.set(r,c(c([],u(n),!1),[t],!1))}else{n=this.resMiddleware.get(r)||[];this.resMiddleware.set(r,c(c([],u(n),!1),[t],!1))}},t.prototype.getMiddleware=function(t){var e,r,n,o,i=[],s=[];try{for(var l=a(this.reqMiddleware.entries()),f=l.next();!f.done;f=l.next()){var h=u(f.value,2),d=h[0],p=h[1];"string"==typeof d&&"*"!==d&&d===t&&i.push.apply(i,c([],u(p),!1)),d instanceof RegExp&&d.test(t)&&i.push.apply(i,c([],u(p),!1)),"*"===d&&i.push.apply(i,c([],u(p),!1))}}catch(t){e={error:t}}finally{try{f&&!f.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var y=a(this.resMiddleware.entries()),E=y.next();!E.done;E=y.next()){var R=u(E.value,2);d=R[0],p=R[1];"string"==typeof d&&"*"!==d&&d===t&&s.push.apply(s,c([],u(p),!1)),d instanceof RegExp&&d.test(t)&&s.push.apply(s,c([],u(p),!1)),"*"===d&&s.push.apply(s,c([],u(p),!1))}}catch(t){n={error:t}}finally{try{E&&!E.done&&(o=y.return)&&o.call(y)}finally{if(n)throw n.error}}return[i,s]},t}());function _(t){return t=t||Object.create(null),{on:function(e,r){(t[e]||(t[e]=[])).push(r)},off:function(e,r){t[e]&&t[e].splice(t[e].indexOf(r)>>>0,1)},emit:function(e,r){(t[e]||[]).slice().map((function(t){t(r)})),(t["*"]||[]).slice().map((function(t){t(e,r)}))}}}var T=function(){function t(){var t=this;this.handlers={},this.emitter=new _(this.handlers),this.off=this.emitter.off.bind(this),this.emit=this.emitter.emit.bind(this),this.promise=new Promise((function(e,r){t.resolve=e,t.reject=r})),this.then=this.promise.then.bind(this.promise)}return t.prototype.resetHandlers=function(){for(var t in this.handlers)delete this.handlers[t]},t.prototype.on=function(t,e){return this.emitter.on(t,e),this},t.prototype.once=function(t,e){var r=this;this.emitter.on(t,(function(n){e(n),r.removeEventListener(t)}))},t.prototype.addEventListener=function(t,e){this.emitter.on(t,e)},t.prototype.removeEventListener=function(t,e){if(t)return e?this.emitter.off(t,e):void delete this.handlers[t];this.handlers={}},t.prototype.onError=function(t){this.emitter.on("error",t),this.removeEventListener("*")},t.prototype.onData=function(t){this.emitter.on("data",t),this.removeEventListener("*")},t.prototype.listenerCount=function(t){var e=0;return Object.keys(this.handlers).forEach((function(r){t===r&&(e+=1)})),e},t}();t.EventEmitter=T,t.GET_TX_ATTEMPTS=33,t.HTTPProvider=R,t.Signer=r,t.composeMiddleware=E,t.isValidResponse=function(t){return!("2.0"!==t.jsonrpc||"1"!==t.id&&1!==t.id||!t.error&&!t.result)},t.performBatchRPC=y,t.performRPC=p,t.sign=function(t,e,r){var n=r.value;return r.value=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return i(this,void 0,void 0,(function(){var r;return s(this,(function(o){switch(o.label){case 0:return n&&t.bytes?[4,this.signer.sign(t)]:[3,2];case 1:return r=o.sent(),[2,n.call.apply(n,c([this,r],u(e),!1))];case 2:return[2]}}))}))},r},Object.defineProperty(t,"__esModule",{value:!0})}));

2

package.json
{
"name": "@zilliqa-js/core",
"version": "3.4.2-rc.0",
"version": "3.4.2",
"description": "Core abstractions that power the zilliqa JS client.",

@@ -5,0 +5,0 @@ "main": "dist/cjs/src/index.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc