Skip to content

Instantly share code, notes, and snippets.

@cuongdcdev
Created September 12, 2022 20:56
Show Gist options
  • Save cuongdcdev/988690941c58b704161c3f98ac0020fe to your computer and use it in GitHub Desktop.
Save cuongdcdev/988690941c58b704161c3f98ac0020fe to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
(function (modules, entry, mainEntry, parcelRequireName, globalName) {
/* eslint-disable no-undef */
var globalObject =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
/* eslint-enable no-undef */
// Save the require from previous bundle to this closure if any
var previousRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
var cache = previousRequire.cache || {};
// Do not use `require` to prevent Webpack from trying to bundle this call
var nodeRequire =
typeof module !== 'undefined' &&
typeof module.require === 'function' &&
module.require.bind(module);
function newRequire(name, jumped) {
if (!cache[name]) {
if (!modules[name]) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
if (!jumped && currentRequire) {
return currentRequire(name, true);
}
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) {
return previousRequire(name, true);
}
// Try the node require function if it exists.
if (nodeRequire && typeof name === 'string') {
return nodeRequire(name);
}
var err = new Error("Cannot find module '" + name + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
}
localRequire.resolve = resolve;
localRequire.cache = {};
var module = (cache[name] = new newRequire.Module(name));
modules[name][0].call(
module.exports,
localRequire,
module,
module.exports,
this
);
}
return cache[name].exports;
function localRequire(x) {
var res = localRequire.resolve(x);
return res === false ? {} : newRequire(res);
}
function resolve(x) {
var id = modules[name][1][x];
return id != null ? id : x;
}
}
function Module(moduleName) {
this.id = moduleName;
this.bundle = newRequire;
this.exports = {};
}
newRequire.isParcelRequire = true;
newRequire.Module = Module;
newRequire.modules = modules;
newRequire.cache = cache;
newRequire.parent = previousRequire;
newRequire.register = function (id, exports) {
modules[id] = [
function (require, module) {
module.exports = exports;
},
{},
];
};
Object.defineProperty(newRequire, 'root', {
get: function () {
return globalObject[parcelRequireName];
},
});
globalObject[parcelRequireName] = newRequire;
for (var i = 0; i < entry.length; i++) {
newRequire(entry[i]);
}
if (mainEntry) {
// Expose entry point to Node, AMD or browser globals
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
var mainExports = newRequire(mainEntry);
// CommonJS
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = mainExports;
// RequireJS
} else if (typeof define === 'function' && define.amd) {
define(function () {
return mainExports;
});
// <script>
} else if (globalName) {
this[globalName] = mainExports;
}
}
})({"gkqJn":[function(require,module,exports) {
"use strict";
var global = arguments[3];
var HMR_HOST = null;
var HMR_PORT = null;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d6ea1d42532a7575";
module.bundle.HMR_BUNDLE_ID = "4792c8ecfa6734ea";
/* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, chrome, browser, globalThis, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: mixed;
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
interface ExtensionContext {
runtime: {|
reload(): void,
getURL(url: string): string;
getManifest(): {manifest_version: number, ...};
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
declare var chrome: ExtensionContext;
declare var browser: ExtensionContext;
declare var __parcel__import__: (string) => Promise<void>;
declare var __parcel__importScripts__: (string) => Promise<void>;
declare var globalThis: typeof self;
declare var ServiceWorkerGlobalScope: Object;
*/ var OVERLAY_ID = "__parcel__error__overlay__";
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData,
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function(fn) {
this._acceptCallbacks.push(fn || function() {});
},
dispose: function(fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData = undefined;
}
module.bundle.Module = Module;
var checkedAssets, acceptedAssets, assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf("http") === 0 ? location.hostname : "localhost");
}
function getPort() {
return HMR_PORT || location.port;
} // eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== "undefined") {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == "https:" && !/localhost|127.0.0.1|0.0.0.0/.test(hostname) ? "wss" : "ws";
var ws = new WebSocket(protocol + "://" + hostname + (port ? ":" + port : "") + "/"); // Web extension context
var extCtx = typeof chrome === "undefined" ? typeof browser === "undefined" ? null : browser : chrome; // Safari doesn't support sourceURL in error stacks.
// eval may also be disabled via CSP, so do a quick check.
var supportsSourceURL = false;
try {
(0, eval)('throw new Error("test"); //# sourceURL=test.js');
} catch (err) {
supportsSourceURL = err.stack.includes("test.js");
} // $FlowFixMe
ws.onmessage = async function(event) {
checkedAssets = {} /*: {|[string]: boolean|} */ ;
acceptedAssets = {} /*: {|[string]: boolean|} */ ;
assetsToAccept = [];
var data = JSON.parse(event.data);
if (data.type === "update") {
// Remove error overlay if there is one
if (typeof document !== "undefined") removeErrorOverlay();
let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH); // Handle HMR Update
let handled = assets.every((asset)=>{
return asset.type === "css" || asset.type === "js" && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
});
if (handled) {
console.clear(); // Dispatch custom event so other runtimes (e.g React Refresh) are aware.
if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") window.dispatchEvent(new CustomEvent("parcelhmraccept"));
await hmrApplyUpdates(assets);
for(var i = 0; i < assetsToAccept.length; i++){
var id = assetsToAccept[i][1];
if (!acceptedAssets[id]) hmrAcceptRun(assetsToAccept[i][0], id);
}
} else fullReload();
}
if (data.type === "error") {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi){
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + "\n" + stack + "\n\n" + ansiDiagnostic.hints.join("\n"));
}
if (typeof document !== "undefined") {
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html); // $FlowFixMe
document.body.appendChild(overlay);
}
}
};
ws.onerror = function(e) {
console.error(e.message);
};
ws.onclose = function() {
console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
};
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log("[parcel] ✨ Error resolved");
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement("div");
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics){
let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
return `${p}
<a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
${frame.code}`;
}, "") : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
🚨 ${diagnostic.message}
</div>
<pre>${stack}</pre>
<div>
${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + "</div>").join("")}
</div>
${diagnostic.documentation ? `<div>📝 <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ""}
</div>
`;
}
errorHTML += "</div>";
overlay.innerHTML = errorHTML;
return overlay;
}
function fullReload() {
if ("reload" in location) location.reload();
else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
var modules = bundle.modules;
if (!modules) return [];
var parents = [];
var k, d, dep;
for(k in modules)for(d in modules[k][1]){
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
bundle,
k
]);
}
if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
return parents;
}
function updateLink(link) {
var newLink = link.cloneNode();
newLink.onload = function() {
if (link.parentNode !== null) // $FlowFixMe
link.parentNode.removeChild(link);
};
newLink.setAttribute("href", link.getAttribute("href").split("?")[0] + "?" + Date.now()); // $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) return;
cssTimeout = setTimeout(function() {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for(var i = 0; i < links.length; i++){
// $FlowFixMe[incompatible-type]
var href = links[i].getAttribute("href");
var hostname = getHostname();
var servedFromHMRServer = hostname === "localhost" ? new RegExp("^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):" + getPort()).test(href) : href.indexOf(hostname + ":" + getPort());
var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) updateLink(links[i]);
}
cssTimeout = null;
}, 50);
}
function hmrDownload(asset) {
if (asset.type === "js") {
if (typeof document !== "undefined") {
let script = document.createElement("script");
script.src = asset.url + "?t=" + Date.now();
if (asset.outputFormat === "esmodule") script.type = "module";
return new Promise((resolve, reject)=>{
var _document$head;
script.onload = ()=>resolve(script);
script.onerror = reject;
(_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
});
} else if (typeof importScripts === "function") {
// Worker scripts
if (asset.outputFormat === "esmodule") return import(asset.url + "?t=" + Date.now());
else return new Promise((resolve, reject)=>{
try {
importScripts(asset.url + "?t=" + Date.now());
resolve();
} catch (err) {
reject(err);
}
});
}
}
}
async function hmrApplyUpdates(assets) {
global.parcelHotUpdate = Object.create(null);
let scriptsToRemove;
try {
// If sourceURL comments aren't supported in eval, we need to load
// the update from the dev server over HTTP so that stack traces
// are correct in errors/logs. This is much slower than eval, so
// we only do it if needed (currently just Safari).
// https://bugs.webkit.org/show_bug.cgi?id=137297
// This path is also taken if a CSP disallows eval.
if (!supportsSourceURL) {
let promises = assets.map((asset)=>{
var _hmrDownload;
return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
// Web extension bugfix for Chromium
// https://bugs.chromium.org/p/chromium/issues/detail?id=1255412#c12
if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3) {
if (typeof ServiceWorkerGlobalScope != "undefined" && global instanceof ServiceWorkerGlobalScope) {
extCtx.runtime.reload();
return;
}
asset.url = extCtx.runtime.getURL("/__parcel_hmr_proxy__?url=" + encodeURIComponent(asset.url + "?t=" + Date.now()));
return hmrDownload(asset);
}
throw err;
});
});
scriptsToRemove = await Promise.all(promises);
}
assets.forEach(function(asset) {
hmrApply(module.bundle.root, asset);
});
} finally{
delete global.parcelHotUpdate;
if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
if (script) {
var _document$head2;
(_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
}
});
}
}
function hmrApply(bundle, asset) {
var modules = bundle.modules;
if (!modules) return;
if (asset.type === "css") reloadCSS();
else if (asset.type === "js") {
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
if (modules[asset.id]) {
// Remove dependencies that are removed and will become orphaned.
// This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
let oldDeps = modules[asset.id][1];
for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
let id = oldDeps[dep];
let parents = getParents(module.bundle.root, id);
if (parents.length === 1) hmrDelete(module.bundle.root, id);
}
}
if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
// support for source maps is better with eval.
(0, eval)(asset.output);
// $FlowFixMe
let fn = global.parcelHotUpdate[asset.id];
modules[asset.id] = [
fn,
deps
];
} else if (bundle.parent) hmrApply(bundle.parent, asset);
}
}
function hmrDelete(bundle, id) {
let modules = bundle.modules;
if (!modules) return;
if (modules[id]) {
// Collect dependencies that will become orphaned when this module is deleted.
let deps = modules[id][1];
let orphans = [];
for(let dep in deps){
let parents = getParents(module.bundle.root, deps[dep]);
if (parents.length === 1) orphans.push(deps[dep]);
} // Delete the module. This must be done before deleting dependencies in case of circular dependencies.
delete modules[id];
delete bundle.cache[id]; // Now delete the orphans.
orphans.forEach((id)=>{
hmrDelete(module.bundle.root, id);
});
} else if (bundle.parent) hmrDelete(bundle.parent, id);
}
function hmrAcceptCheck(bundle, id, depsByBundle) {
if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
// Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
let parents = getParents(module.bundle.root, id);
let accepted = false;
while(parents.length > 0){
let v = parents.shift();
let a = hmrAcceptCheckOne(v[0], v[1], null);
if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
accepted = true;
else {
// Otherwise, queue the parents in the next level upward.
let p = getParents(module.bundle.root, v[1]);
if (p.length === 0) {
// If there are no parents, then we've reached an entry without accepting. Reload.
accepted = false;
break;
}
parents.push(...p);
}
}
return accepted;
}
function hmrAcceptCheckOne(bundle, id, depsByBundle) {
var modules = bundle.modules;
if (!modules) return;
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) return true;
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) return true;
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToAccept.push([
bundle,
id
]);
if (!cached || cached.hot && cached.hot._acceptCallbacks.length) return true;
}
function hmrAcceptRun(bundle, id) {
var cached = bundle.cache[id];
bundle.hotData = {};
if (cached && cached.hot) cached.hot.data = bundle.hotData;
if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
cb(bundle.hotData);
});
delete bundle.cache[id];
bundle(id);
cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) cached.hot._acceptCallbacks.forEach(function(cb) {
var assetsToAlsoAccept = cb(function() {
return getParents(module.bundle.root, id);
});
if (assetsToAlsoAccept && assetsToAccept.length) // $FlowFixMe[method-unbinding]
assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
});
acceptedAssets[id] = true;
}
},{}],"6068g":[function(require,module,exports) {
var _runtime = require("regenerator-runtime/runtime");
var _nearInterface = require("./near-interface");
var _nearWallet = require("./near-wallet");
var _gamelogic = require("./gamelogic");
// create the Wallet and the Contract
const wallet = new (0, _nearWallet.Wallet)({
contractId: "dev-1662841077356-64060527250788"
});
const contract = new (0, _nearInterface.Contract)({
wallet: wallet
});
// Setup on page load
window.onload = async ()=>{
//near logic
window.isSignedIn = await wallet.startUp();
if (isSignedIn) signedInFlow();
else signedOutFlow();
//start game logic
(0, _gamelogic.gameLogic)();
await getHighScores();
};
// Button clicks
document.querySelector("#sign-in-button").onclick = ()=>{
console.log("sigout");
wallet.signIn();
};
document.querySelector("#sign-out-button").onclick = ()=>{
wallet.signOut();
};
// Take the new greeting and send it to the contract
// async function doUserAction(event) {
// event.preventDefault();
// const { greeting } = event.target.elements;
// document.querySelector('#signed-in-flow main')
// .classList.add('please-wait');
// await contract.setGreeting(greeting.value);
// // ===== Fetch the data from the blockchain =====
// // await getHighScores();
// document.querySelector('#signed-in-flow main').classList.remove('please-wait');
// }
// Get greeting from the contract on chain
async function getHighScores() {
let listScore = document.getElementById("highScore");
listScore.innerHTML = "loading...";
const hs = await contract.get_scores();
listScore.innerHTML = "";
console.log("top high scores", hs);
hs.sort((a, b)=>{
if (a.score == b.score) return 0;
return a.score > b.score ? -1 : 1;
});
hs.map((s)=>{
let l = document.createElement("li");
l.appendChild(document.createTextNode(`${s.name} - ${s.score}`));
listScore.appendChild(l);
});
// document.querySelectorAll('[data-behavior=greeting]').forEach(el => {
// el.innerText = currentGreeting;
// el.value = currentGreeting;
// });
}
window.saveScoreToNear = async function() {
let listScore = document.getElementById("highScore");
let s = window.getScore();
if (isSignedIn) {
listScore.innerHTML = "loading...";
await contract.set_score(s);
console.log("Save new score to NEAR ", s);
await getHighScores();
}
console.log("called save score to near | score: ", s);
};
// Display the signed-out-flow container
function signedOutFlow() {
document.querySelector("#signed-in-flow").style.display = "none";
document.querySelector("#signed-out-flow").style.display = "block";
}
// Displaying the signed in flow container and fill in account-specific data
function signedInFlow() {
document.querySelector("#signed-out-flow").style.display = "none";
document.querySelector("#signed-in-flow").style.display = "block";
document.querySelectorAll("[data-behavior=account-id]").forEach((el)=>{
el.innerText = wallet.accountId;
});
}
},{"regenerator-runtime/runtime":"dXNgZ","./near-interface":"aahG8","./near-wallet":"dg9wB","./gamelogic":"k1BQ9"}],"dXNgZ":[function(require,module,exports) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ var runtime = function(exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function() {
return this;
});
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) // This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = GeneratorFunctionPrototype;
define(Gp, "constructor", GeneratorFunctionPrototype);
define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction");
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
[
"next",
"throw",
"return"
].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction" : false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return {
__await: arg
};
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") reject(record.arg);
else {
var result = record.arg;
var value = result.value;
if (value && typeof value === "object" && hasOwn.call(value, "__await")) return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = // If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function() {
return this;
});
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) throw new Error("Generator is already running");
if (state === GenStateCompleted) {
if (method === "throw") throw arg;
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while(true){
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") // Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") context.abrupt("return", context.arg);
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done ? GenStateCompleted : GenStateSuspendedYield;
if (record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") // If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
context.method = "throw";
context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (!info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else // Re-yield the result returned by the delegate method.
return info;
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
define(Gp, iteratorSymbol, function() {
return this;
});
define(Gp, "toString", function() {
return "[object Generator]";
});
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
if (1 in locs) entry.catchLoc = locs[1];
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [
{
tryLoc: "root"
}
];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for(var key in object)keys.push(key);
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while(keys.length){
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if (typeof iterable.next === "function") return iterable;
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while(++i < iterable.length)if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return {
next: doneResult
};
}
exports.values = values;
function doneResult() {
return {
value: undefined,
done: true
};
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for(var name in this)// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) this[name] = undefined;
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") throw rootRecord.arg;
return this.rval;
},
dispatchException: function(exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !!caught;
}
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") // Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, true);
else if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, true);
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else throw new Error("try statement without catch or finally");
}
}
},
abrupt: function(type, arg) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) // Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") throw record.arg;
if (record.type === "break" || record.type === "continue") this.next = record.arg;
else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) this.next = afterLoc;
return ContinueSentinel;
},
finish: function(finallyLoc) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") // Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(module.exports);
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, in modern engines
// we can explicitly access globalThis. In older engines we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
if (typeof globalThis === "object") globalThis.regeneratorRuntime = runtime;
else Function("r", "regeneratorRuntime = r")(runtime);
}
},{}],"aahG8":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
parcelHelpers.export(exports, "Contract", ()=>Contract);
class Contract {
wallet;
constructor({ wallet }){
this.wallet = wallet;
}
async getGreeting() {
return await this.wallet.viewMethod({
method: "get_greeting"
});
}
async setGreeting(greeting) {
return await this.wallet.callMethod({
method: "set_greeting",
args: {
message: greeting
}
});
}
async set_score(score) {
return await this.wallet.callMethod({
method: "set_score",
args: {
score: score
}
});
}
async get_scores() {
return await this.wallet.viewMethod({
method: "get_scores",
args: {}
});
}
}
},{"@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}],"gkKU3":[function(require,module,exports) {
exports.interopDefault = function(a) {
return a && a.__esModule ? a : {
default: a
};
};
exports.defineInteropFlag = function(a) {
Object.defineProperty(a, "__esModule", {
value: true
});
};
exports.exportAll = function(source, dest) {
Object.keys(source).forEach(function(key) {
if (key === "default" || key === "__esModule" || dest.hasOwnProperty(key)) return;
Object.defineProperty(dest, key, {
enumerable: true,
get: function() {
return source[key];
}
});
});
return dest;
};
exports.export = function(dest, destName, get) {
Object.defineProperty(dest, destName, {
enumerable: true,
get: get
});
};
},{}],"dg9wB":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
// Wallet that simplifies using the wallet selector
parcelHelpers.export(exports, "Wallet", ()=>Wallet);
// near api js
var _nearApiJs = require("near-api-js");
// wallet selector UI
var _stylesCss = require("@near-wallet-selector/modal-ui/styles.css");
var _modalUi = require("@near-wallet-selector/modal-ui");
// wallet selector options
var _core = require("@near-wallet-selector/core");
var _nearWallet = require("@near-wallet-selector/near-wallet");
var _myNearWallet = require("@near-wallet-selector/my-near-wallet");
var Buffer = require("buffer").Buffer;
const THIRTY_TGAS = "30000000000000";
const NO_DEPOSIT = "0";
class Wallet {
walletSelector;
wallet;
accountId;
contractId;
constructor({ contractId }){
this.contractId = contractId;
}
// To be called when the website loads
async startUp() {
this.walletSelector = await (0, _core.setupWalletSelector)({
network: "testnet",
modules: [
(0, _nearWallet.setupNearWallet)(),
(0, _myNearWallet.setupMyNearWallet)()
]
});
const isSignedIn = this.walletSelector.isSignedIn();
if (isSignedIn) {
const { accounts } = this.walletSelector.store.getState();
this.wallet = await this.walletSelector.wallet();
this.accountId = accounts[0].accountId;
}
return isSignedIn;
}
// Sign-in method
signIn() {
const description = "Please select a wallet to sign in.";
const modal = (0, _modalUi.setupModal)(this.walletSelector, {
contractId: this.contractId,
description
});
modal.show();
}
// Sign-out method
signOut() {
this.wallet.signOut();
this.wallet = this.accountId = this.contractId = null;
window.location.replace(window.location.origin + window.location.pathname);
}
// Make a read-only call to retrieve information from the network
async viewMethod({ contractId =this.contractId , method , args ={} }) {
const { network } = this.walletSelector.options;
const provider = new (0, _nearApiJs.providers).JsonRpcProvider({
url: network.nodeUrl
});
let res = await provider.query({
request_type: "call_function",
account_id: contractId,
method_name: method,
args_base64: Buffer.from(JSON.stringify(args)).toString("base64"),
finality: "optimistic"
});
return JSON.parse(Buffer.from(res.result).toString());
}
// Call a method that changes the contract's state
async callMethod({ contractId =this.contractId , method , args ={} , gas =THIRTY_TGAS , deposit =NO_DEPOSIT }) {
const { accountId } = this.walletSelector.store.getState().accounts[0];
// Sign a transaction with the "FunctionCall" action
return await this.wallet.signAndSendTransaction({
signerId: accountId,
receiverId: contractId,
actions: [
{
type: "FunctionCall",
params: {
methodName: method,
args,
gas,
deposit
}
},
]
});
}
// Get transaction result from the network
async getTransactionResult(txhash) {
const { network } = this.walletSelector.options;
const provider = new (0, _nearApiJs.providers).JsonRpcProvider({
url: network.nodeUrl
});
// Retrieve transaction result from the network
const transaction = await provider.txStatus(txhash, "unnused");
return (0, _nearApiJs.providers).getTransactionLastResult(transaction);
}
}
},{"near-api-js":"ohc3m","@near-wallet-selector/modal-ui":"1nDKo","@near-wallet-selector/core":"eEY3a","@near-wallet-selector/my-near-wallet":"bYYGG","buffer":"dvCeB","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3","@near-wallet-selector/near-wallet":"aOKgp","@near-wallet-selector/modal-ui/styles.css":"b4TAP"}],"ohc3m":[function(require,module,exports) {
"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: function() {
return m[k];
}
});
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __exportStar = this && this.__exportStar || function(m, exports1) {
for(var p in m)if (p !== "default" && !exports1.hasOwnProperty(p)) __createBinding(exports1, m, p);
};
Object.defineProperty(exports, "__esModule", {
value: true
});
/** @hidden @module */ exports.keyStores = __importStar(require("./key_stores/browser-index"));
__exportStar(require("./common-index"), exports);
__exportStar(require("./browser-connect"), exports);
require("error-polyfill");
},{"./key_stores/browser-index":"aBfSM","./common-index":"gtZXS","./browser-connect":"7yTE6","error-polyfill":"2YFhR"}],"aBfSM":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MergeKeyStore = exports.BrowserLocalStorageKeyStore = exports.InMemoryKeyStore = exports.KeyStore = void 0;
/** @hidden @module */ const keystore_1 = require("./keystore");
Object.defineProperty(exports, "KeyStore", {
enumerable: true,
get: function() {
return keystore_1.KeyStore;
}
});
const in_memory_key_store_1 = require("./in_memory_key_store");
Object.defineProperty(exports, "InMemoryKeyStore", {
enumerable: true,
get: function() {
return in_memory_key_store_1.InMemoryKeyStore;
}
});
const browser_local_storage_key_store_1 = require("./browser_local_storage_key_store");
Object.defineProperty(exports, "BrowserLocalStorageKeyStore", {
enumerable: true,
get: function() {
return browser_local_storage_key_store_1.BrowserLocalStorageKeyStore;
}
});
const merge_key_store_1 = require("./merge_key_store");
Object.defineProperty(exports, "MergeKeyStore", {
enumerable: true,
get: function() {
return merge_key_store_1.MergeKeyStore;
}
});
},{"./keystore":"5Moei","./in_memory_key_store":"fTfs7","./browser_local_storage_key_store":"l5Tuv","./merge_key_store":"kgqhu"}],"5Moei":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.KeyStore = void 0;
/**
* KeyStores are passed to {@link Near} via {@link NearConfig}
* and are used by the {@link InMemorySigner} to sign transactions.
*
* @example {@link connect}
*/ class KeyStore {
}
exports.KeyStore = KeyStore;
},{}],"fTfs7":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InMemoryKeyStore = void 0;
const keystore_1 = require("./keystore");
const key_pair_1 = require("../utils/key_pair");
/**
* Simple in-memory keystore for mainly for testing purposes.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores, utils } from 'near-api-js';
*
* const privateKey = '.......';
* const keyPair = utils.KeyPair.fromString(privateKey);
*
* const keyStore = new keyStores.InMemoryKeyStore();
* keyStore.setKey('testnet', 'example-account.testnet', keyPair);
*
* const config = {
* keyStore, // instance of InMemoryKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/ class InMemoryKeyStore extends keystore_1.KeyStore {
constructor(){
super();
this.keys = {};
}
/**
* Stores a {@KeyPair} in in-memory storage item
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/ async setKey(networkId, accountId, keyPair) {
this.keys[`${accountId}:${networkId}`] = keyPair.toString();
}
/**
* Gets a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/ async getKey(networkId, accountId) {
const value = this.keys[`${accountId}:${networkId}`];
if (!value) return null;
return key_pair_1.KeyPair.fromString(value);
}
/**
* Removes a {@link KeyPair} from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/ async removeKey(networkId, accountId) {
delete this.keys[`${accountId}:${networkId}`];
}
/**
* Removes all {@link KeyPairs} from in-memory storage
*/ async clear() {
this.keys = {};
}
/**
* Get the network(s) from in-memory storage
* @returns {Promise<string[]>}
*/ async getNetworks() {
const result = new Set();
Object.keys(this.keys).forEach((key)=>{
const parts = key.split(":");
result.add(parts[1]);
});
return Array.from(result.values());
}
/**
* Gets the account(s) from in-memory storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns{Promise<string[]>}
*/ async getAccounts(networkId) {
const result = new Array();
Object.keys(this.keys).forEach((key)=>{
const parts = key.split(":");
if (parts[parts.length - 1] === networkId) result.push(parts.slice(0, parts.length - 1).join(":"));
});
return result;
}
/** @hidden */ toString() {
return "InMemoryKeyStore";
}
}
exports.InMemoryKeyStore = InMemoryKeyStore;
},{"./keystore":"5Moei","../utils/key_pair":"kBQFP"}],"kBQFP":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.KeyPairEd25519 = exports.KeyPair = exports.PublicKey = exports.KeyType = void 0;
const tweetnacl_1 = __importDefault(require("tweetnacl"));
const serialize_1 = require("./serialize");
const enums_1 = require("./enums");
/** All supported key types */ var KeyType;
(function(KeyType) {
KeyType[KeyType["ED25519"] = 0] = "ED25519";
})(KeyType = exports.KeyType || (exports.KeyType = {}));
function key_type_to_str(keyType) {
switch(keyType){
case KeyType.ED25519:
return "ed25519";
default:
throw new Error(`Unknown key type ${keyType}`);
}
}
function str_to_key_type(keyType) {
switch(keyType.toLowerCase()){
case "ed25519":
return KeyType.ED25519;
default:
throw new Error(`Unknown key type ${keyType}`);
}
}
/**
* PublicKey representation that has type and bytes of the key.
*/ class PublicKey extends enums_1.Assignable {
static from(value) {
if (typeof value === "string") return PublicKey.fromString(value);
return value;
}
static fromString(encodedKey) {
const parts = encodedKey.split(":");
if (parts.length === 1) return new PublicKey({
keyType: KeyType.ED25519,
data: serialize_1.base_decode(parts[0])
});
else if (parts.length === 2) return new PublicKey({
keyType: str_to_key_type(parts[0]),
data: serialize_1.base_decode(parts[1])
});
else throw new Error("Invalid encoded key format, must be <curve>:<encoded key>");
}
toString() {
return `${key_type_to_str(this.keyType)}:${serialize_1.base_encode(this.data)}`;
}
verify(message, signature) {
switch(this.keyType){
case KeyType.ED25519:
return tweetnacl_1.default.sign.detached.verify(message, signature, this.data);
default:
throw new Error(`Unknown key type ${this.keyType}`);
}
}
}
exports.PublicKey = PublicKey;
class KeyPair {
/**
* @param curve Name of elliptical curve, case-insensitive
* @returns Random KeyPair based on the curve
*/ static fromRandom(curve) {
switch(curve.toUpperCase()){
case "ED25519":
return KeyPairEd25519.fromRandom();
default:
throw new Error(`Unknown curve ${curve}`);
}
}
static fromString(encodedKey) {
const parts = encodedKey.split(":");
if (parts.length === 1) return new KeyPairEd25519(parts[0]);
else if (parts.length === 2) switch(parts[0].toUpperCase()){
case "ED25519":
return new KeyPairEd25519(parts[1]);
default:
throw new Error(`Unknown curve: ${parts[0]}`);
}
else throw new Error("Invalid encoded key format, must be <curve>:<encoded key>");
}
}
exports.KeyPair = KeyPair;
/**
* This class provides key pair functionality for Ed25519 curve:
* generating key pairs, encoding key pairs, signing and verifying.
*/ class KeyPairEd25519 extends KeyPair {
/**
* Construct an instance of key pair given a secret key.
* It's generally assumed that these are encoded in base58.
* @param {string} secretKey
*/ constructor(secretKey){
super();
const keyPair = tweetnacl_1.default.sign.keyPair.fromSecretKey(serialize_1.base_decode(secretKey));
this.publicKey = new PublicKey({
keyType: KeyType.ED25519,
data: keyPair.publicKey
});
this.secretKey = secretKey;
}
/**
* Generate a new random keypair.
* @example
* const keyRandom = KeyPair.fromRandom();
* keyRandom.publicKey
* // returns [PUBLIC_KEY]
*
* keyRandom.secretKey
* // returns [SECRET_KEY]
*/ static fromRandom() {
const newKeyPair = tweetnacl_1.default.sign.keyPair();
return new KeyPairEd25519(serialize_1.base_encode(newKeyPair.secretKey));
}
sign(message) {
const signature = tweetnacl_1.default.sign.detached(message, serialize_1.base_decode(this.secretKey));
return {
signature,
publicKey: this.publicKey
};
}
verify(message, signature) {
return this.publicKey.verify(message, signature);
}
toString() {
return `ed25519:${this.secretKey}`;
}
getPublicKey() {
return this.publicKey;
}
}
exports.KeyPairEd25519 = KeyPairEd25519;
},{"tweetnacl":"3J9rh","./serialize":"dUoM9","./enums":"kjmPo"}],"3J9rh":[function(require,module,exports) {
(function(nacl) {
"use strict";
// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/
var gf = function(init) {
var i, r = new Float64Array(16);
if (init) for(i = 0; i < init.length; i++)r[i] = init[i];
return r;
};
// Pluggable, initialized in high-level API below.
var randombytes = function() {
throw new Error("no PRNG");
};
var _0 = new Uint8Array(16);
var _9 = new Uint8Array(32);
_9[0] = 9;
var gf0 = gf(), gf1 = gf([
1
]), _121665 = gf([
0xdb41,
1
]), D = gf([
0x78a3,
0x1359,
0x4dca,
0x75eb,
0xd8ab,
0x4141,
0x0a4d,
0x0070,
0xe898,
0x7779,
0x4079,
0x8cc7,
0xfe73,
0x2b6f,
0x6cee,
0x5203
]), D2 = gf([
0xf159,
0x26b2,
0x9b94,
0xebd6,
0xb156,
0x8283,
0x149a,
0x00e0,
0xd130,
0xeef3,
0x80f2,
0x198e,
0xfce7,
0x56df,
0xd9dc,
0x2406
]), X = gf([
0xd51a,
0x8f25,
0x2d60,
0xc956,
0xa7b2,
0x9525,
0xc760,
0x692c,
0xdc5c,
0xfdd6,
0xe231,
0xc0a4,
0x53fe,
0xcd6e,
0x36d3,
0x2169
]), Y = gf([
0x6658,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666,
0x6666
]), I = gf([
0xa0b0,
0x4a0e,
0x1b27,
0xc4ee,
0xe478,
0xad2f,
0x1806,
0x2f43,
0xd7a7,
0x3dfb,
0x0099,
0x2b4d,
0xdf0b,
0x4fc1,
0x2480,
0x2b83
]);
function ts64(x, i, h, l) {
x[i] = h >> 24 & 0xff;
x[i + 1] = h >> 16 & 0xff;
x[i + 2] = h >> 8 & 0xff;
x[i + 3] = h & 0xff;
x[i + 4] = l >> 24 & 0xff;
x[i + 5] = l >> 16 & 0xff;
x[i + 6] = l >> 8 & 0xff;
x[i + 7] = l & 0xff;
}
function vn(x, xi, y, yi, n) {
var i, d = 0;
for(i = 0; i < n; i++)d |= x[xi + i] ^ y[yi + i];
return (1 & d - 1 >>> 8) - 1;
}
function crypto_verify_16(x, xi, y, yi) {
return vn(x, xi, y, yi, 16);
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x, xi, y, yi, 32);
}
function core_salsa20(o, p, k, c) {
var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
for(var i = 0; i < 20; i += 2){
u = x0 + x12 | 0;
x4 ^= u << 7 | u >>> 25;
u = x4 + x0 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x4 | 0;
x12 ^= u << 13 | u >>> 19;
u = x12 + x8 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x1 | 0;
x9 ^= u << 7 | u >>> 25;
u = x9 + x5 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x9 | 0;
x1 ^= u << 13 | u >>> 19;
u = x1 + x13 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x6 | 0;
x14 ^= u << 7 | u >>> 25;
u = x14 + x10 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x14 | 0;
x6 ^= u << 13 | u >>> 19;
u = x6 + x2 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x11 | 0;
x3 ^= u << 7 | u >>> 25;
u = x3 + x15 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x3 | 0;
x11 ^= u << 13 | u >>> 19;
u = x11 + x7 | 0;
x15 ^= u << 18 | u >>> 14;
u = x0 + x3 | 0;
x1 ^= u << 7 | u >>> 25;
u = x1 + x0 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x1 | 0;
x3 ^= u << 13 | u >>> 19;
u = x3 + x2 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x4 | 0;
x6 ^= u << 7 | u >>> 25;
u = x6 + x5 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x6 | 0;
x4 ^= u << 13 | u >>> 19;
u = x4 + x7 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x9 | 0;
x11 ^= u << 7 | u >>> 25;
u = x11 + x10 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x11 | 0;
x9 ^= u << 13 | u >>> 19;
u = x9 + x8 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x14 | 0;
x12 ^= u << 7 | u >>> 25;
u = x12 + x15 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x12 | 0;
x14 ^= u << 13 | u >>> 19;
u = x14 + x13 | 0;
x15 ^= u << 18 | u >>> 14;
}
x0 = x0 + j0 | 0;
x1 = x1 + j1 | 0;
x2 = x2 + j2 | 0;
x3 = x3 + j3 | 0;
x4 = x4 + j4 | 0;
x5 = x5 + j5 | 0;
x6 = x6 + j6 | 0;
x7 = x7 + j7 | 0;
x8 = x8 + j8 | 0;
x9 = x9 + j9 | 0;
x10 = x10 + j10 | 0;
x11 = x11 + j11 | 0;
x12 = x12 + j12 | 0;
x13 = x13 + j13 | 0;
x14 = x14 + j14 | 0;
x15 = x15 + j15 | 0;
o[0] = x0 >>> 0 & 0xff;
o[1] = x0 >>> 8 & 0xff;
o[2] = x0 >>> 16 & 0xff;
o[3] = x0 >>> 24 & 0xff;
o[4] = x1 >>> 0 & 0xff;
o[5] = x1 >>> 8 & 0xff;
o[6] = x1 >>> 16 & 0xff;
o[7] = x1 >>> 24 & 0xff;
o[8] = x2 >>> 0 & 0xff;
o[9] = x2 >>> 8 & 0xff;
o[10] = x2 >>> 16 & 0xff;
o[11] = x2 >>> 24 & 0xff;
o[12] = x3 >>> 0 & 0xff;
o[13] = x3 >>> 8 & 0xff;
o[14] = x3 >>> 16 & 0xff;
o[15] = x3 >>> 24 & 0xff;
o[16] = x4 >>> 0 & 0xff;
o[17] = x4 >>> 8 & 0xff;
o[18] = x4 >>> 16 & 0xff;
o[19] = x4 >>> 24 & 0xff;
o[20] = x5 >>> 0 & 0xff;
o[21] = x5 >>> 8 & 0xff;
o[22] = x5 >>> 16 & 0xff;
o[23] = x5 >>> 24 & 0xff;
o[24] = x6 >>> 0 & 0xff;
o[25] = x6 >>> 8 & 0xff;
o[26] = x6 >>> 16 & 0xff;
o[27] = x6 >>> 24 & 0xff;
o[28] = x7 >>> 0 & 0xff;
o[29] = x7 >>> 8 & 0xff;
o[30] = x7 >>> 16 & 0xff;
o[31] = x7 >>> 24 & 0xff;
o[32] = x8 >>> 0 & 0xff;
o[33] = x8 >>> 8 & 0xff;
o[34] = x8 >>> 16 & 0xff;
o[35] = x8 >>> 24 & 0xff;
o[36] = x9 >>> 0 & 0xff;
o[37] = x9 >>> 8 & 0xff;
o[38] = x9 >>> 16 & 0xff;
o[39] = x9 >>> 24 & 0xff;
o[40] = x10 >>> 0 & 0xff;
o[41] = x10 >>> 8 & 0xff;
o[42] = x10 >>> 16 & 0xff;
o[43] = x10 >>> 24 & 0xff;
o[44] = x11 >>> 0 & 0xff;
o[45] = x11 >>> 8 & 0xff;
o[46] = x11 >>> 16 & 0xff;
o[47] = x11 >>> 24 & 0xff;
o[48] = x12 >>> 0 & 0xff;
o[49] = x12 >>> 8 & 0xff;
o[50] = x12 >>> 16 & 0xff;
o[51] = x12 >>> 24 & 0xff;
o[52] = x13 >>> 0 & 0xff;
o[53] = x13 >>> 8 & 0xff;
o[54] = x13 >>> 16 & 0xff;
o[55] = x13 >>> 24 & 0xff;
o[56] = x14 >>> 0 & 0xff;
o[57] = x14 >>> 8 & 0xff;
o[58] = x14 >>> 16 & 0xff;
o[59] = x14 >>> 24 & 0xff;
o[60] = x15 >>> 0 & 0xff;
o[61] = x15 >>> 8 & 0xff;
o[62] = x15 >>> 16 & 0xff;
o[63] = x15 >>> 24 & 0xff;
}
function core_hsalsa20(o, p, k, c) {
var j0 = c[0] & 0xff | (c[1] & 0xff) << 8 | (c[2] & 0xff) << 16 | (c[3] & 0xff) << 24, j1 = k[0] & 0xff | (k[1] & 0xff) << 8 | (k[2] & 0xff) << 16 | (k[3] & 0xff) << 24, j2 = k[4] & 0xff | (k[5] & 0xff) << 8 | (k[6] & 0xff) << 16 | (k[7] & 0xff) << 24, j3 = k[8] & 0xff | (k[9] & 0xff) << 8 | (k[10] & 0xff) << 16 | (k[11] & 0xff) << 24, j4 = k[12] & 0xff | (k[13] & 0xff) << 8 | (k[14] & 0xff) << 16 | (k[15] & 0xff) << 24, j5 = c[4] & 0xff | (c[5] & 0xff) << 8 | (c[6] & 0xff) << 16 | (c[7] & 0xff) << 24, j6 = p[0] & 0xff | (p[1] & 0xff) << 8 | (p[2] & 0xff) << 16 | (p[3] & 0xff) << 24, j7 = p[4] & 0xff | (p[5] & 0xff) << 8 | (p[6] & 0xff) << 16 | (p[7] & 0xff) << 24, j8 = p[8] & 0xff | (p[9] & 0xff) << 8 | (p[10] & 0xff) << 16 | (p[11] & 0xff) << 24, j9 = p[12] & 0xff | (p[13] & 0xff) << 8 | (p[14] & 0xff) << 16 | (p[15] & 0xff) << 24, j10 = c[8] & 0xff | (c[9] & 0xff) << 8 | (c[10] & 0xff) << 16 | (c[11] & 0xff) << 24, j11 = k[16] & 0xff | (k[17] & 0xff) << 8 | (k[18] & 0xff) << 16 | (k[19] & 0xff) << 24, j12 = k[20] & 0xff | (k[21] & 0xff) << 8 | (k[22] & 0xff) << 16 | (k[23] & 0xff) << 24, j13 = k[24] & 0xff | (k[25] & 0xff) << 8 | (k[26] & 0xff) << 16 | (k[27] & 0xff) << 24, j14 = k[28] & 0xff | (k[29] & 0xff) << 8 | (k[30] & 0xff) << 16 | (k[31] & 0xff) << 24, j15 = c[12] & 0xff | (c[13] & 0xff) << 8 | (c[14] & 0xff) << 16 | (c[15] & 0xff) << 24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
for(var i = 0; i < 20; i += 2){
u = x0 + x12 | 0;
x4 ^= u << 7 | u >>> 25;
u = x4 + x0 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x4 | 0;
x12 ^= u << 13 | u >>> 19;
u = x12 + x8 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x1 | 0;
x9 ^= u << 7 | u >>> 25;
u = x9 + x5 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x9 | 0;
x1 ^= u << 13 | u >>> 19;
u = x1 + x13 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x6 | 0;
x14 ^= u << 7 | u >>> 25;
u = x14 + x10 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x14 | 0;
x6 ^= u << 13 | u >>> 19;
u = x6 + x2 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x11 | 0;
x3 ^= u << 7 | u >>> 25;
u = x3 + x15 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x3 | 0;
x11 ^= u << 13 | u >>> 19;
u = x11 + x7 | 0;
x15 ^= u << 18 | u >>> 14;
u = x0 + x3 | 0;
x1 ^= u << 7 | u >>> 25;
u = x1 + x0 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x1 | 0;
x3 ^= u << 13 | u >>> 19;
u = x3 + x2 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x4 | 0;
x6 ^= u << 7 | u >>> 25;
u = x6 + x5 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x6 | 0;
x4 ^= u << 13 | u >>> 19;
u = x4 + x7 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x9 | 0;
x11 ^= u << 7 | u >>> 25;
u = x11 + x10 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x11 | 0;
x9 ^= u << 13 | u >>> 19;
u = x9 + x8 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x14 | 0;
x12 ^= u << 7 | u >>> 25;
u = x12 + x15 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x12 | 0;
x14 ^= u << 13 | u >>> 19;
u = x14 + x13 | 0;
x15 ^= u << 18 | u >>> 14;
}
o[0] = x0 >>> 0 & 0xff;
o[1] = x0 >>> 8 & 0xff;
o[2] = x0 >>> 16 & 0xff;
o[3] = x0 >>> 24 & 0xff;
o[4] = x5 >>> 0 & 0xff;
o[5] = x5 >>> 8 & 0xff;
o[6] = x5 >>> 16 & 0xff;
o[7] = x5 >>> 24 & 0xff;
o[8] = x10 >>> 0 & 0xff;
o[9] = x10 >>> 8 & 0xff;
o[10] = x10 >>> 16 & 0xff;
o[11] = x10 >>> 24 & 0xff;
o[12] = x15 >>> 0 & 0xff;
o[13] = x15 >>> 8 & 0xff;
o[14] = x15 >>> 16 & 0xff;
o[15] = x15 >>> 24 & 0xff;
o[16] = x6 >>> 0 & 0xff;
o[17] = x6 >>> 8 & 0xff;
o[18] = x6 >>> 16 & 0xff;
o[19] = x6 >>> 24 & 0xff;
o[20] = x7 >>> 0 & 0xff;
o[21] = x7 >>> 8 & 0xff;
o[22] = x7 >>> 16 & 0xff;
o[23] = x7 >>> 24 & 0xff;
o[24] = x8 >>> 0 & 0xff;
o[25] = x8 >>> 8 & 0xff;
o[26] = x8 >>> 16 & 0xff;
o[27] = x8 >>> 24 & 0xff;
o[28] = x9 >>> 0 & 0xff;
o[29] = x9 >>> 8 & 0xff;
o[30] = x9 >>> 16 & 0xff;
o[31] = x9 >>> 24 & 0xff;
}
function crypto_core_salsa20(out, inp, k, c) {
core_salsa20(out, inp, k, c);
}
function crypto_core_hsalsa20(out, inp, k, c) {
core_hsalsa20(out, inp, k, c);
}
var sigma = new Uint8Array([
101,
120,
112,
97,
110,
100,
32,
51,
50,
45,
98,
121,
116,
101,
32,
107
]);
// "expand 32-byte k"
function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for(i = 0; i < 16; i++)z[i] = 0;
for(i = 0; i < 8; i++)z[i] = n[i];
while(b >= 64){
crypto_core_salsa20(x, z, k, sigma);
for(i = 0; i < 64; i++)c[cpos + i] = m[mpos + i] ^ x[i];
u = 1;
for(i = 8; i < 16; i++){
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
mpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x, z, k, sigma);
for(i = 0; i < b; i++)c[cpos + i] = m[mpos + i] ^ x[i];
}
return 0;
}
function crypto_stream_salsa20(c, cpos, b, n, k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for(i = 0; i < 16; i++)z[i] = 0;
for(i = 0; i < 8; i++)z[i] = n[i];
while(b >= 64){
crypto_core_salsa20(x, z, k, sigma);
for(i = 0; i < 64; i++)c[cpos + i] = x[i];
u = 1;
for(i = 8; i < 16; i++){
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x, z, k, sigma);
for(i = 0; i < b; i++)c[cpos + i] = x[i];
}
return 0;
}
function crypto_stream(c, cpos, d, n, k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s, n, k, sigma);
var sn = new Uint8Array(8);
for(var i = 0; i < 8; i++)sn[i] = n[i + 16];
return crypto_stream_salsa20(c, cpos, d, sn, s);
}
function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s, n, k, sigma);
var sn = new Uint8Array(8);
for(var i = 0; i < 8; i++)sn[i] = n[i + 16];
return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s);
}
/*
* Port of Andrew Moon's Poly1305-donna-16. Public domain.
* https://github.com/floodyberry/poly1305-donna
*/ var poly1305 = function(key) {
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.leftover = 0;
this.fin = 0;
var t0, t1, t2, t3, t4, t5, t6, t7;
t0 = key[0] & 0xff | (key[1] & 0xff) << 8;
this.r[0] = t0 & 0x1fff;
t1 = key[2] & 0xff | (key[3] & 0xff) << 8;
this.r[1] = (t0 >>> 13 | t1 << 3) & 0x1fff;
t2 = key[4] & 0xff | (key[5] & 0xff) << 8;
this.r[2] = (t1 >>> 10 | t2 << 6) & 0x1f03;
t3 = key[6] & 0xff | (key[7] & 0xff) << 8;
this.r[3] = (t2 >>> 7 | t3 << 9) & 0x1fff;
t4 = key[8] & 0xff | (key[9] & 0xff) << 8;
this.r[4] = (t3 >>> 4 | t4 << 12) & 0x00ff;
this.r[5] = t4 >>> 1 & 0x1ffe;
t5 = key[10] & 0xff | (key[11] & 0xff) << 8;
this.r[6] = (t4 >>> 14 | t5 << 2) & 0x1fff;
t6 = key[12] & 0xff | (key[13] & 0xff) << 8;
this.r[7] = (t5 >>> 11 | t6 << 5) & 0x1f81;
t7 = key[14] & 0xff | (key[15] & 0xff) << 8;
this.r[8] = (t6 >>> 8 | t7 << 8) & 0x1fff;
this.r[9] = t7 >>> 5 & 0x007f;
this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
};
poly1305.prototype.blocks = function(m, mpos, bytes) {
var hibit = this.fin ? 0 : 2048;
var t0, t1, t2, t3, t4, t5, t6, t7, c;
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9];
var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9];
while(bytes >= 16){
t0 = m[mpos + 0] & 0xff | (m[mpos + 1] & 0xff) << 8;
h0 += t0 & 0x1fff;
t1 = m[mpos + 2] & 0xff | (m[mpos + 3] & 0xff) << 8;
h1 += (t0 >>> 13 | t1 << 3) & 0x1fff;
t2 = m[mpos + 4] & 0xff | (m[mpos + 5] & 0xff) << 8;
h2 += (t1 >>> 10 | t2 << 6) & 0x1fff;
t3 = m[mpos + 6] & 0xff | (m[mpos + 7] & 0xff) << 8;
h3 += (t2 >>> 7 | t3 << 9) & 0x1fff;
t4 = m[mpos + 8] & 0xff | (m[mpos + 9] & 0xff) << 8;
h4 += (t3 >>> 4 | t4 << 12) & 0x1fff;
h5 += t4 >>> 1 & 0x1fff;
t5 = m[mpos + 10] & 0xff | (m[mpos + 11] & 0xff) << 8;
h6 += (t4 >>> 14 | t5 << 2) & 0x1fff;
t6 = m[mpos + 12] & 0xff | (m[mpos + 13] & 0xff) << 8;
h7 += (t5 >>> 11 | t6 << 5) & 0x1fff;
t7 = m[mpos + 14] & 0xff | (m[mpos + 15] & 0xff) << 8;
h8 += (t6 >>> 8 | t7 << 8) & 0x1fff;
h9 += t7 >>> 5 | hibit;
c = 0;
d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 0x1fff;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 0x1fff;
d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 0x1fff;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 0x1fff;
d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 0x1fff;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 0x1fff;
d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 0x1fff;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 0x1fff;
d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = d4 >>> 13;
d4 &= 0x1fff;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 0x1fff;
d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = d5 >>> 13;
d5 &= 0x1fff;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 0x1fff;
d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = d6 >>> 13;
d6 &= 0x1fff;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 0x1fff;
d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = d7 >>> 13;
d7 &= 0x1fff;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 0x1fff;
d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = d8 >>> 13;
d8 &= 0x1fff;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 0x1fff;
d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = d9 >>> 13;
d9 &= 0x1fff;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += d9 >>> 13;
d9 &= 0x1fff;
c = (c << 2) + c | 0;
c = c + d0 | 0;
d0 = c & 0x1fff;
c = c >>> 13;
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this.h[0] = h0;
this.h[1] = h1;
this.h[2] = h2;
this.h[3] = h3;
this.h[4] = h4;
this.h[5] = h5;
this.h[6] = h6;
this.h[7] = h7;
this.h[8] = h8;
this.h[9] = h9;
};
poly1305.prototype.finish = function(mac, macpos) {
var g = new Uint16Array(10);
var c, mask, f, i;
if (this.leftover) {
i = this.leftover;
this.buffer[i++] = 1;
for(; i < 16; i++)this.buffer[i] = 0;
this.fin = 1;
this.blocks(this.buffer, 0, 16);
}
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
for(i = 2; i < 10; i++){
this.h[i] += c;
c = this.h[i] >>> 13;
this.h[i] &= 0x1fff;
}
this.h[0] += c * 5;
c = this.h[0] >>> 13;
this.h[0] &= 0x1fff;
this.h[1] += c;
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
this.h[2] += c;
g[0] = this.h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for(i = 1; i < 10; i++){
g[i] = this.h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= 8192;
mask = (c ^ 1) - 1;
for(i = 0; i < 10; i++)g[i] &= mask;
mask = ~mask;
for(i = 0; i < 10; i++)this.h[i] = this.h[i] & mask | g[i];
this.h[0] = (this.h[0] | this.h[1] << 13) & 0xffff;
this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 0xffff;
this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 0xffff;
this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 0xffff;
this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 0xffff;
this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 0xffff;
this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 0xffff;
this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 0xffff;
f = this.h[0] + this.pad[0];
this.h[0] = f & 0xffff;
for(i = 1; i < 8; i++){
f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0;
this.h[i] = f & 0xffff;
}
mac[macpos + 0] = this.h[0] >>> 0 & 0xff;
mac[macpos + 1] = this.h[0] >>> 8 & 0xff;
mac[macpos + 2] = this.h[1] >>> 0 & 0xff;
mac[macpos + 3] = this.h[1] >>> 8 & 0xff;
mac[macpos + 4] = this.h[2] >>> 0 & 0xff;
mac[macpos + 5] = this.h[2] >>> 8 & 0xff;
mac[macpos + 6] = this.h[3] >>> 0 & 0xff;
mac[macpos + 7] = this.h[3] >>> 8 & 0xff;
mac[macpos + 8] = this.h[4] >>> 0 & 0xff;
mac[macpos + 9] = this.h[4] >>> 8 & 0xff;
mac[macpos + 10] = this.h[5] >>> 0 & 0xff;
mac[macpos + 11] = this.h[5] >>> 8 & 0xff;
mac[macpos + 12] = this.h[6] >>> 0 & 0xff;
mac[macpos + 13] = this.h[6] >>> 8 & 0xff;
mac[macpos + 14] = this.h[7] >>> 0 & 0xff;
mac[macpos + 15] = this.h[7] >>> 8 & 0xff;
};
poly1305.prototype.update = function(m, mpos, bytes) {
var i, want;
if (this.leftover) {
want = 16 - this.leftover;
if (want > bytes) want = bytes;
for(i = 0; i < want; i++)this.buffer[this.leftover + i] = m[mpos + i];
bytes -= want;
mpos += want;
this.leftover += want;
if (this.leftover < 16) return;
this.blocks(this.buffer, 0, 16);
this.leftover = 0;
}
if (bytes >= 16) {
want = bytes - bytes % 16;
this.blocks(m, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for(i = 0; i < bytes; i++)this.buffer[this.leftover + i] = m[mpos + i];
this.leftover += bytes;
}
};
function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
var s = new poly1305(k);
s.update(m, mpos, n);
s.finish(out, outpos);
return 0;
}
function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
var x = new Uint8Array(16);
crypto_onetimeauth(x, 0, m, mpos, n, k);
return crypto_verify_16(h, hpos, x, 0);
}
function crypto_secretbox(c, m, d, n, k) {
var i;
if (d < 32) return -1;
crypto_stream_xor(c, 0, m, 0, d, n, k);
crypto_onetimeauth(c, 16, c, 32, d - 32, c);
for(i = 0; i < 16; i++)c[i] = 0;
return 0;
}
function crypto_secretbox_open(m, c, d, n, k) {
var i;
var x = new Uint8Array(32);
if (d < 32) return -1;
crypto_stream(x, 0, 32, n, k);
if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1;
crypto_stream_xor(m, 0, c, 0, d, n, k);
for(i = 0; i < 32; i++)m[i] = 0;
return 0;
}
function set25519(r, a) {
var i;
for(i = 0; i < 16; i++)r[i] = a[i] | 0;
}
function car25519(o) {
var i, v, c = 1;
for(i = 0; i < 16; i++){
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p, q, b) {
var t, c = ~(b - 1);
for(var i = 0; i < 16; i++){
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o, n) {
var i, j, b;
var m = gf(), t = gf();
for(i = 0; i < 16; i++)t[i] = n[i];
car25519(t);
car25519(t);
car25519(t);
for(j = 0; j < 2; j++){
m[0] = t[0] - 0xffed;
for(i = 1; i < 15; i++){
m[i] = t[i] - 0xffff - (m[i - 1] >> 16 & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - (m[14] >> 16 & 1);
b = m[15] >> 16 & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for(i = 0; i < 16; i++){
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function neq25519(a, b) {
var c = new Uint8Array(32), d = new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return crypto_verify_32(c, 0, d, 0);
}
function par25519(a) {
var d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o, n) {
var i;
for(i = 0; i < 16; i++)o[i] = n[2 * i] + (n[2 * i + 1] << 8);
o[15] &= 0x7fff;
}
function A(o, a, b) {
for(var i = 0; i < 16; i++)o[i] = a[i] + b[i];
}
function Z(o, a, b) {
for(var i = 0; i < 16; i++)o[i] = a[i] - b[i];
}
function M(o, a, b) {
var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
// second car
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function S(o, a) {
M(o, a, a);
}
function inv25519(o, i) {
var c = gf();
var a;
for(a = 0; a < 16; a++)c[a] = i[a];
for(a = 253; a >= 0; a--){
S(c, c);
if (a !== 2 && a !== 4) M(c, c, i);
}
for(a = 0; a < 16; a++)o[a] = c[a];
}
function pow2523(o, i) {
var c = gf();
var a;
for(a = 0; a < 16; a++)c[a] = i[a];
for(a = 250; a >= 0; a--){
S(c, c);
if (a !== 1) M(c, c, i);
}
for(a = 0; a < 16; a++)o[a] = c[a];
}
function crypto_scalarmult(q, n, p) {
var z = new Uint8Array(32);
var x = new Float64Array(80), r, i;
var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();
for(i = 0; i < 31; i++)z[i] = n[i];
z[31] = n[31] & 127 | 64;
z[0] &= 248;
unpack25519(x, p);
for(i = 0; i < 16; i++){
b[i] = x[i];
d[i] = a[i] = c[i] = 0;
}
a[0] = d[0] = 1;
for(i = 254; i >= 0; --i){
r = z[i >>> 3] >>> (i & 7) & 1;
sel25519(a, b, r);
sel25519(c, d, r);
A(e, a, c);
Z(a, a, c);
A(c, b, d);
Z(b, b, d);
S(d, e);
S(f, a);
M(a, c, a);
M(c, b, e);
A(e, a, c);
Z(a, a, c);
S(b, a);
Z(c, d, f);
M(a, c, _121665);
A(a, a, d);
M(c, c, a);
M(a, d, f);
M(d, b, x);
S(b, e);
sel25519(a, b, r);
sel25519(c, d, r);
}
for(i = 0; i < 16; i++){
x[i + 16] = a[i];
x[i + 32] = c[i];
x[i + 48] = b[i];
x[i + 64] = d[i];
}
var x32 = x.subarray(32);
var x16 = x.subarray(16);
inv25519(x32, x32);
M(x16, x16, x32);
pack25519(q, x16);
return 0;
}
function crypto_scalarmult_base(q, n) {
return crypto_scalarmult(q, n, _9);
}
function crypto_box_keypair(y, x) {
randombytes(x, 32);
return crypto_scalarmult_base(y, x);
}
function crypto_box_beforenm(k, y, x) {
var s = new Uint8Array(32);
crypto_scalarmult(s, x, y);
return crypto_core_hsalsa20(k, _0, s, sigma);
}
var crypto_box_afternm = crypto_secretbox;
var crypto_box_open_afternm = crypto_secretbox_open;
function crypto_box(c, m, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_afternm(c, m, d, n, k);
}
function crypto_box_open(m, c, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_open_afternm(m, c, d, n, k);
}
var K = [
0x428a2f98,
0xd728ae22,
0x71374491,
0x23ef65cd,
0xb5c0fbcf,
0xec4d3b2f,
0xe9b5dba5,
0x8189dbbc,
0x3956c25b,
0xf348b538,
0x59f111f1,
0xb605d019,
0x923f82a4,
0xaf194f9b,
0xab1c5ed5,
0xda6d8118,
0xd807aa98,
0xa3030242,
0x12835b01,
0x45706fbe,
0x243185be,
0x4ee4b28c,
0x550c7dc3,
0xd5ffb4e2,
0x72be5d74,
0xf27b896f,
0x80deb1fe,
0x3b1696b1,
0x9bdc06a7,
0x25c71235,
0xc19bf174,
0xcf692694,
0xe49b69c1,
0x9ef14ad2,
0xefbe4786,
0x384f25e3,
0x0fc19dc6,
0x8b8cd5b5,
0x240ca1cc,
0x77ac9c65,
0x2de92c6f,
0x592b0275,
0x4a7484aa,
0x6ea6e483,
0x5cb0a9dc,
0xbd41fbd4,
0x76f988da,
0x831153b5,
0x983e5152,
0xee66dfab,
0xa831c66d,
0x2db43210,
0xb00327c8,
0x98fb213f,
0xbf597fc7,
0xbeef0ee4,
0xc6e00bf3,
0x3da88fc2,
0xd5a79147,
0x930aa725,
0x06ca6351,
0xe003826f,
0x14292967,
0x0a0e6e70,
0x27b70a85,
0x46d22ffc,
0x2e1b2138,
0x5c26c926,
0x4d2c6dfc,
0x5ac42aed,
0x53380d13,
0x9d95b3df,
0x650a7354,
0x8baf63de,
0x766a0abb,
0x3c77b2a8,
0x81c2c92e,
0x47edaee6,
0x92722c85,
0x1482353b,
0xa2bfe8a1,
0x4cf10364,
0xa81a664b,
0xbc423001,
0xc24b8b70,
0xd0f89791,
0xc76c51a3,
0x0654be30,
0xd192e819,
0xd6ef5218,
0xd6990624,
0x5565a910,
0xf40e3585,
0x5771202a,
0x106aa070,
0x32bbd1b8,
0x19a4c116,
0xb8d2d0c8,
0x1e376c08,
0x5141ab53,
0x2748774c,
0xdf8eeb99,
0x34b0bcb5,
0xe19b48a8,
0x391c0cb3,
0xc5c95a63,
0x4ed8aa4a,
0xe3418acb,
0x5b9cca4f,
0x7763e373,
0x682e6ff3,
0xd6b2b8a3,
0x748f82ee,
0x5defb2fc,
0x78a5636f,
0x43172f60,
0x84c87814,
0xa1f0ab72,
0x8cc70208,
0x1a6439ec,
0x90befffa,
0x23631e28,
0xa4506ceb,
0xde82bde9,
0xbef9a3f7,
0xb2c67915,
0xc67178f2,
0xe372532b,
0xca273ece,
0xea26619c,
0xd186b8c7,
0x21c0c207,
0xeada7dd6,
0xcde0eb1e,
0xf57d4f7f,
0xee6ed178,
0x06f067aa,
0x72176fba,
0x0a637dc5,
0xa2c898a6,
0x113f9804,
0xbef90dae,
0x1b710b35,
0x131c471b,
0x28db77f5,
0x23047d84,
0x32caab7b,
0x40c72493,
0x3c9ebe0a,
0x15c9bebc,
0x431d67c4,
0x9c100d4c,
0x4cc5d4be,
0xcb3e42b6,
0x597f299c,
0xfc657e2a,
0x5fcb6fab,
0x3ad6faec,
0x6c44198c,
0x4a475817
];
function crypto_hashblocks_hl(hh, hl, m, n) {
var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d;
var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
var pos = 0;
while(n >= 128){
for(i = 0; i < 16; i++){
j = 8 * i + pos;
wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3];
wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7];
}
for(i = 0; i < 80; i++){
bh0 = ah0;
bh1 = ah1;
bh2 = ah2;
bh3 = ah3;
bh4 = ah4;
bh5 = ah5;
bh6 = ah6;
bh7 = ah7;
bl0 = al0;
bl1 = al1;
bl2 = al2;
bl3 = al3;
bl4 = al4;
bl5 = al5;
bl6 = al6;
bl7 = al7;
// add
h = ah7;
l = al7;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
// Sigma1
h = (ah4 >>> 14 | al4 << 18) ^ (ah4 >>> 18 | al4 << 14) ^ (al4 >>> 9 | ah4 << 23);
l = (al4 >>> 14 | ah4 << 18) ^ (al4 >>> 18 | ah4 << 14) ^ (ah4 >>> 9 | al4 << 23);
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// Ch
h = ah4 & ah5 ^ ~ah4 & ah6;
l = al4 & al5 ^ ~al4 & al6;
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// K
h = K[i * 2];
l = K[i * 2 + 1];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// w
h = wh[i % 16];
l = wl[i % 16];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
th = c & 0xffff | d << 16;
tl = a & 0xffff | b << 16;
// add
h = th;
l = tl;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
// Sigma0
h = (ah0 >>> 28 | al0 << 4) ^ (al0 >>> 2 | ah0 << 30) ^ (al0 >>> 7 | ah0 << 25);
l = (al0 >>> 28 | ah0 << 4) ^ (ah0 >>> 2 | al0 << 30) ^ (ah0 >>> 7 | al0 << 25);
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// Maj
h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
l = al0 & al1 ^ al0 & al2 ^ al1 & al2;
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh7 = c & 0xffff | d << 16;
bl7 = a & 0xffff | b << 16;
// add
h = bh3;
l = bl3;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = th;
l = tl;
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh3 = c & 0xffff | d << 16;
bl3 = a & 0xffff | b << 16;
ah1 = bh0;
ah2 = bh1;
ah3 = bh2;
ah4 = bh3;
ah5 = bh4;
ah6 = bh5;
ah7 = bh6;
ah0 = bh7;
al1 = bl0;
al2 = bl1;
al3 = bl2;
al4 = bl3;
al5 = bl4;
al6 = bl5;
al7 = bl6;
al0 = bl7;
if (i % 16 === 15) for(j = 0; j < 16; j++){
// add
h = wh[j];
l = wl[j];
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = wh[(j + 9) % 16];
l = wl[(j + 9) % 16];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// sigma0
th = wh[(j + 1) % 16];
tl = wl[(j + 1) % 16];
h = (th >>> 1 | tl << 31) ^ (th >>> 8 | tl << 24) ^ th >>> 7;
l = (tl >>> 1 | th << 31) ^ (tl >>> 8 | th << 24) ^ (tl >>> 7 | th << 25);
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
// sigma1
th = wh[(j + 14) % 16];
tl = wl[(j + 14) % 16];
h = (th >>> 19 | tl << 13) ^ (tl >>> 29 | th << 3) ^ th >>> 6;
l = (tl >>> 19 | th << 13) ^ (th >>> 29 | tl << 3) ^ (tl >>> 6 | th << 26);
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
wh[j] = c & 0xffff | d << 16;
wl[j] = a & 0xffff | b << 16;
}
}
// add
h = ah0;
l = al0;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[0];
l = hl[0];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[0] = ah0 = c & 0xffff | d << 16;
hl[0] = al0 = a & 0xffff | b << 16;
h = ah1;
l = al1;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[1];
l = hl[1];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[1] = ah1 = c & 0xffff | d << 16;
hl[1] = al1 = a & 0xffff | b << 16;
h = ah2;
l = al2;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[2];
l = hl[2];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[2] = ah2 = c & 0xffff | d << 16;
hl[2] = al2 = a & 0xffff | b << 16;
h = ah3;
l = al3;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[3];
l = hl[3];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[3] = ah3 = c & 0xffff | d << 16;
hl[3] = al3 = a & 0xffff | b << 16;
h = ah4;
l = al4;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[4];
l = hl[4];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[4] = ah4 = c & 0xffff | d << 16;
hl[4] = al4 = a & 0xffff | b << 16;
h = ah5;
l = al5;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[5];
l = hl[5];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[5] = ah5 = c & 0xffff | d << 16;
hl[5] = al5 = a & 0xffff | b << 16;
h = ah6;
l = al6;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[6];
l = hl[6];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[6] = ah6 = c & 0xffff | d << 16;
hl[6] = al6 = a & 0xffff | b << 16;
h = ah7;
l = al7;
a = l & 0xffff;
b = l >>> 16;
c = h & 0xffff;
d = h >>> 16;
h = hh[7];
l = hl[7];
a += l & 0xffff;
b += l >>> 16;
c += h & 0xffff;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[7] = ah7 = c & 0xffff | d << 16;
hl[7] = al7 = a & 0xffff | b << 16;
pos += 128;
n -= 128;
}
return n;
}
function crypto_hash(out, m, n) {
var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n;
hh[0] = 0x6a09e667;
hh[1] = 0xbb67ae85;
hh[2] = 0x3c6ef372;
hh[3] = 0xa54ff53a;
hh[4] = 0x510e527f;
hh[5] = 0x9b05688c;
hh[6] = 0x1f83d9ab;
hh[7] = 0x5be0cd19;
hl[0] = 0xf3bcc908;
hl[1] = 0x84caa73b;
hl[2] = 0xfe94f82b;
hl[3] = 0x5f1d36f1;
hl[4] = 0xade682d1;
hl[5] = 0x2b3e6c1f;
hl[6] = 0xfb41bd6b;
hl[7] = 0x137e2179;
crypto_hashblocks_hl(hh, hl, m, n);
n %= 128;
for(i = 0; i < n; i++)x[i] = m[b - n + i];
x[n] = 128;
n = 256 - 128 * (n < 112 ? 1 : 0);
x[n - 9] = 0;
ts64(x, n - 8, b / 0x20000000 | 0, b << 3);
crypto_hashblocks_hl(hh, hl, x, n);
for(i = 0; i < 8; i++)ts64(out, 8 * i, hh[i], hl[i]);
return 0;
}
function add(p, q) {
var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
Z(a, p[1], p[0]);
Z(t, q[1], q[0]);
M(a, a, t);
A(b, p[0], p[1]);
A(t, q[0], q[1]);
M(b, b, t);
M(c, p[3], q[3]);
M(c, c, D2);
M(d, p[2], q[2]);
A(d, d, d);
Z(e, b, a);
Z(f, d, c);
A(g, d, c);
A(h, b, a);
M(p[0], e, f);
M(p[1], h, g);
M(p[2], g, f);
M(p[3], e, h);
}
function cswap(p, q, b) {
var i;
for(i = 0; i < 4; i++)sel25519(p[i], q[i], b);
}
function pack(r, p) {
var tx = gf(), ty = gf(), zi = gf();
inv25519(zi, p[2]);
M(tx, p[0], zi);
M(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function scalarmult(p, q, s) {
var b, i;
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for(i = 255; i >= 0; --i){
b = s[i / 8 | 0] >> (i & 7) & 1;
cswap(p, q, b);
add(q, p);
add(p, p);
cswap(p, q, b);
}
}
function scalarbase(p, s) {
var q = [
gf(),
gf(),
gf(),
gf()
];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
M(q[3], X, Y);
scalarmult(p, q, s);
}
function crypto_sign_keypair(pk, sk, seeded) {
var d = new Uint8Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
];
var i;
if (!seeded) randombytes(sk, 32);
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
scalarbase(p, d);
pack(pk, p);
for(i = 0; i < 32; i++)sk[i + 32] = pk[i];
return 0;
}
var L = new Float64Array([
0xed,
0xd3,
0xf5,
0x5c,
0x1a,
0x63,
0x12,
0x58,
0xd6,
0x9c,
0xf7,
0xa2,
0xde,
0xf9,
0xde,
0x14,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0x10
]);
function modL(r, x) {
var carry, i, j, k;
for(i = 63; i >= 32; --i){
carry = 0;
for(j = i - 32, k = i - 12; j < k; ++j){
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = Math.floor((x[j] + 128) / 256);
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for(j = 0; j < 32; j++){
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for(j = 0; j < 32; j++)x[j] -= carry * L[j];
for(i = 0; i < 32; i++){
x[i + 1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function reduce(r) {
var x = new Float64Array(64), i;
for(i = 0; i < 64; i++)x[i] = r[i];
for(i = 0; i < 64; i++)r[i] = 0;
modL(r, x);
}
// Note: difference from C - smlen returned, not passed as argument.
function crypto_sign(sm, m, n, sk) {
var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
var i, j, x = new Float64Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
];
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
var smlen = n + 64;
for(i = 0; i < n; i++)sm[64 + i] = m[i];
for(i = 0; i < 32; i++)sm[32 + i] = d[32 + i];
crypto_hash(r, sm.subarray(32), n + 32);
reduce(r);
scalarbase(p, r);
pack(sm, p);
for(i = 32; i < 64; i++)sm[i] = sk[i];
crypto_hash(h, sm, n + 64);
reduce(h);
for(i = 0; i < 64; i++)x[i] = 0;
for(i = 0; i < 32; i++)x[i] = r[i];
for(i = 0; i < 32; i++)for(j = 0; j < 32; j++)x[i + j] += h[i] * d[j];
modL(sm.subarray(32), x);
return smlen;
}
function unpackneg(r, p) {
var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
S(den2, den);
S(den4, den2);
M(den6, den4, den2);
M(t, den6, num);
M(t, t, den);
pow2523(t, t);
M(t, t, num);
M(t, t, den);
M(t, t, den);
M(r[0], t, den);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) M(r[0], r[0], I);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) return -1;
if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]);
M(r[3], r[0], r[1]);
return 0;
}
function crypto_sign_open(m, sm, n, pk) {
var i;
var t = new Uint8Array(32), h = new Uint8Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
], q = [
gf(),
gf(),
gf(),
gf()
];
if (n < 64) return -1;
if (unpackneg(q, pk)) return -1;
for(i = 0; i < n; i++)m[i] = sm[i];
for(i = 0; i < 32; i++)m[i + 32] = pk[i];
crypto_hash(h, m, n);
reduce(h);
scalarmult(p, q, h);
scalarbase(q, sm.subarray(32));
add(p, q);
pack(t, p);
n -= 64;
if (crypto_verify_32(sm, 0, t, 0)) {
for(i = 0; i < n; i++)m[i] = 0;
return -1;
}
for(i = 0; i < n; i++)m[i] = sm[i + 64];
return n;
}
var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64;
nacl.lowlevel = {
crypto_core_hsalsa20: crypto_core_hsalsa20,
crypto_stream_xor: crypto_stream_xor,
crypto_stream: crypto_stream,
crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
crypto_stream_salsa20: crypto_stream_salsa20,
crypto_onetimeauth: crypto_onetimeauth,
crypto_onetimeauth_verify: crypto_onetimeauth_verify,
crypto_verify_16: crypto_verify_16,
crypto_verify_32: crypto_verify_32,
crypto_secretbox: crypto_secretbox,
crypto_secretbox_open: crypto_secretbox_open,
crypto_scalarmult: crypto_scalarmult,
crypto_scalarmult_base: crypto_scalarmult_base,
crypto_box_beforenm: crypto_box_beforenm,
crypto_box_afternm: crypto_box_afternm,
crypto_box: crypto_box,
crypto_box_open: crypto_box_open,
crypto_box_keypair: crypto_box_keypair,
crypto_hash: crypto_hash,
crypto_sign: crypto_sign,
crypto_sign_keypair: crypto_sign_keypair,
crypto_sign_open: crypto_sign_open,
crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
crypto_sign_BYTES: crypto_sign_BYTES,
crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
crypto_hash_BYTES: crypto_hash_BYTES,
gf: gf,
D: D,
L: L,
pack25519: pack25519,
unpack25519: unpack25519,
M: M,
A: A,
S: S,
Z: Z,
pow2523: pow2523,
add: add,
set25519: set25519,
modL: modL,
scalarmult: scalarmult,
scalarbase: scalarbase
};
/* High-level API */ function checkLengths(k, n) {
if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size");
if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size");
}
function checkBoxLengths(pk, sk) {
if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size");
if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size");
}
function checkArrayTypes() {
for(var i = 0; i < arguments.length; i++){
if (!(arguments[i] instanceof Uint8Array)) throw new TypeError("unexpected type, use Uint8Array");
}
}
function cleanup(arr) {
for(var i = 0; i < arr.length; i++)arr[i] = 0;
}
nacl.randomBytes = function(n) {
var b = new Uint8Array(n);
randombytes(b, n);
return b;
};
nacl.secretbox = function(msg, nonce, key) {
checkArrayTypes(msg, nonce, key);
checkLengths(key, nonce);
var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
var c = new Uint8Array(m.length);
for(var i = 0; i < msg.length; i++)m[i + crypto_secretbox_ZEROBYTES] = msg[i];
crypto_secretbox(c, m, m.length, nonce, key);
return c.subarray(crypto_secretbox_BOXZEROBYTES);
};
nacl.secretbox.open = function(box, nonce, key) {
checkArrayTypes(box, nonce, key);
checkLengths(key, nonce);
var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
var m = new Uint8Array(c.length);
for(var i = 0; i < box.length; i++)c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
if (c.length < 32) return null;
if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
return m.subarray(crypto_secretbox_ZEROBYTES);
};
nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
nacl.scalarMult = function(n, p) {
checkArrayTypes(n, p);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size");
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult(q, n, p);
return q;
};
nacl.scalarMult.base = function(n) {
checkArrayTypes(n);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult_base(q, n);
return q;
};
nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
nacl.box = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox(msg, nonce, k);
};
nacl.box.before = function(publicKey, secretKey) {
checkArrayTypes(publicKey, secretKey);
checkBoxLengths(publicKey, secretKey);
var k = new Uint8Array(crypto_box_BEFORENMBYTES);
crypto_box_beforenm(k, publicKey, secretKey);
return k;
};
nacl.box.after = nacl.secretbox;
nacl.box.open = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox.open(msg, nonce, k);
};
nacl.box.open.after = nacl.secretbox.open;
nacl.box.keyPair = function() {
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
crypto_box_keypair(pk, sk);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.box.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size");
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
crypto_scalarmult_base(pk, secretKey);
return {
publicKey: pk,
secretKey: new Uint8Array(secretKey)
};
};
nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
nacl.box.nonceLength = crypto_box_NONCEBYTES;
nacl.box.overheadLength = nacl.secretbox.overheadLength;
nacl.sign = function(msg, secretKey) {
checkArrayTypes(msg, secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size");
var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
crypto_sign(signedMsg, msg, msg.length, secretKey);
return signedMsg;
};
nacl.sign.open = function(signedMsg, publicKey) {
checkArrayTypes(signedMsg, publicKey);
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size");
var tmp = new Uint8Array(signedMsg.length);
var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
if (mlen < 0) return null;
var m = new Uint8Array(mlen);
for(var i = 0; i < m.length; i++)m[i] = tmp[i];
return m;
};
nacl.sign.detached = function(msg, secretKey) {
var signedMsg = nacl.sign(msg, secretKey);
var sig = new Uint8Array(crypto_sign_BYTES);
for(var i = 0; i < sig.length; i++)sig[i] = signedMsg[i];
return sig;
};
nacl.sign.detached.verify = function(msg, sig, publicKey) {
checkArrayTypes(msg, sig, publicKey);
if (sig.length !== crypto_sign_BYTES) throw new Error("bad signature size");
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size");
var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
var m = new Uint8Array(crypto_sign_BYTES + msg.length);
var i;
for(i = 0; i < crypto_sign_BYTES; i++)sm[i] = sig[i];
for(i = 0; i < msg.length; i++)sm[i + crypto_sign_BYTES] = msg[i];
return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
};
nacl.sign.keyPair = function() {
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
crypto_sign_keypair(pk, sk);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.sign.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size");
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
for(var i = 0; i < pk.length; i++)pk[i] = secretKey[32 + i];
return {
publicKey: pk,
secretKey: new Uint8Array(secretKey)
};
};
nacl.sign.keyPair.fromSeed = function(seed) {
checkArrayTypes(seed);
if (seed.length !== crypto_sign_SEEDBYTES) throw new Error("bad seed size");
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
for(var i = 0; i < 32; i++)sk[i] = seed[i];
crypto_sign_keypair(pk, sk, true);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
nacl.sign.seedLength = crypto_sign_SEEDBYTES;
nacl.sign.signatureLength = crypto_sign_BYTES;
nacl.hash = function(msg) {
checkArrayTypes(msg);
var h = new Uint8Array(crypto_hash_BYTES);
crypto_hash(h, msg, msg.length);
return h;
};
nacl.hash.hashLength = crypto_hash_BYTES;
nacl.verify = function(x, y) {
checkArrayTypes(x, y);
// Zero length arguments are considered not equal.
if (x.length === 0 || y.length === 0) return false;
if (x.length !== y.length) return false;
return vn(x, 0, y, 0, x.length) === 0 ? true : false;
};
nacl.setPRNG = function(fn) {
randombytes = fn;
};
(function() {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
if (crypto && crypto.getRandomValues) {
// Browsers.
var QUOTA = 65536;
nacl.setPRNG(function(x, n) {
var i, v = new Uint8Array(n);
for(i = 0; i < n; i += QUOTA)crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
for(i = 0; i < n; i++)x[i] = v[i];
cleanup(v);
});
} else {
// Node.js.
crypto = require("crypto");
if (crypto && crypto.randomBytes) nacl.setPRNG(function(x, n) {
var i, v = crypto.randomBytes(n);
for(i = 0; i < n; i++)x[i] = v[i];
cleanup(v);
});
}
})();
})(module.exports ? module.exports : self.nacl = self.nacl || {});
},{"crypto":"jhUEF"}],"jhUEF":[function(require,module,exports) {
"use strict";
},{}],"dUoM9":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var borsh_1 = require("borsh");
Object.defineProperty(exports, "base_encode", {
enumerable: true,
get: function() {
return borsh_1.baseEncode;
}
});
Object.defineProperty(exports, "base_decode", {
enumerable: true,
get: function() {
return borsh_1.baseDecode;
}
});
Object.defineProperty(exports, "serialize", {
enumerable: true,
get: function() {
return borsh_1.serialize;
}
});
Object.defineProperty(exports, "deserialize", {
enumerable: true,
get: function() {
return borsh_1.deserialize;
}
});
Object.defineProperty(exports, "BorshError", {
enumerable: true,
get: function() {
return borsh_1.BorshError;
}
});
Object.defineProperty(exports, "BinaryWriter", {
enumerable: true,
get: function() {
return borsh_1.BinaryWriter;
}
});
Object.defineProperty(exports, "BinaryReader", {
enumerable: true,
get: function() {
return borsh_1.BinaryReader;
}
});
},{"borsh":"4JCmN"}],"4JCmN":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var global = arguments[3];
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: function() {
return m[k];
}
});
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __decorate = this && this.__decorate || function(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.deserializeUnchecked = exports.deserialize = exports.serialize = exports.BinaryReader = exports.BinaryWriter = exports.BorshError = exports.baseDecode = exports.baseEncode = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const bs58_1 = __importDefault(require("bs58"));
// TODO: Make sure this polyfill not included when not required
const encoding = __importStar(require("text-encoding-utf-8"));
const TextDecoder = typeof global.TextDecoder !== "function" ? encoding.TextDecoder : global.TextDecoder;
const textDecoder = new TextDecoder("utf-8", {
fatal: true
});
function baseEncode(value) {
if (typeof value === "string") value = Buffer.from(value, "utf8");
return bs58_1.default.encode(Buffer.from(value));
}
exports.baseEncode = baseEncode;
function baseDecode(value) {
return Buffer.from(bs58_1.default.decode(value));
}
exports.baseDecode = baseDecode;
const INITIAL_LENGTH = 1024;
class BorshError extends Error {
constructor(message){
super(message);
this.fieldPath = [];
this.originalMessage = message;
}
addToFieldPath(fieldName) {
this.fieldPath.splice(0, 0, fieldName);
// NOTE: Modifying message directly as jest doesn't use .toString()
this.message = this.originalMessage + ": " + this.fieldPath.join(".");
}
}
exports.BorshError = BorshError;
/// Binary encoder.
class BinaryWriter {
constructor(){
this.buf = Buffer.alloc(INITIAL_LENGTH);
this.length = 0;
}
maybeResize() {
if (this.buf.length < 16 + this.length) this.buf = Buffer.concat([
this.buf,
Buffer.alloc(INITIAL_LENGTH)
]);
}
writeU8(value) {
this.maybeResize();
this.buf.writeUInt8(value, this.length);
this.length += 1;
}
writeU16(value) {
this.maybeResize();
this.buf.writeUInt16LE(value, this.length);
this.length += 2;
}
writeU32(value) {
this.maybeResize();
this.buf.writeUInt32LE(value, this.length);
this.length += 4;
}
writeU64(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 8)));
}
writeU128(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 16)));
}
writeU256(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 32)));
}
writeU512(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 64)));
}
writeBuffer(buffer) {
// Buffer.from is needed as this.buf.subarray can return plain Uint8Array in browser
this.buf = Buffer.concat([
Buffer.from(this.buf.subarray(0, this.length)),
buffer,
Buffer.alloc(INITIAL_LENGTH)
]);
this.length += buffer.length;
}
writeString(str) {
this.maybeResize();
const b = Buffer.from(str, "utf8");
this.writeU32(b.length);
this.writeBuffer(b);
}
writeFixedArray(array) {
this.writeBuffer(Buffer.from(array));
}
writeArray(array, fn) {
this.maybeResize();
this.writeU32(array.length);
for (const elem of array){
this.maybeResize();
fn(elem);
}
}
toArray() {
return this.buf.subarray(0, this.length);
}
}
exports.BinaryWriter = BinaryWriter;
function handlingRangeError(target, propertyKey, propertyDescriptor) {
const originalMethod = propertyDescriptor.value;
propertyDescriptor.value = function(...args) {
try {
return originalMethod.apply(this, args);
} catch (e) {
if (e instanceof RangeError) {
const code = e.code;
if ([
"ERR_BUFFER_OUT_OF_BOUNDS",
"ERR_OUT_OF_RANGE"
].indexOf(code) >= 0) throw new BorshError("Reached the end of buffer when deserializing");
}
throw e;
}
};
}
class BinaryReader {
constructor(buf){
this.buf = buf;
this.offset = 0;
}
readU8() {
const value = this.buf.readUInt8(this.offset);
this.offset += 1;
return value;
}
readU16() {
const value = this.buf.readUInt16LE(this.offset);
this.offset += 2;
return value;
}
readU32() {
const value = this.buf.readUInt32LE(this.offset);
this.offset += 4;
return value;
}
readU64() {
const buf = this.readBuffer(8);
return new bn_js_1.default(buf, "le");
}
readU128() {
const buf = this.readBuffer(16);
return new bn_js_1.default(buf, "le");
}
readU256() {
const buf = this.readBuffer(32);
return new bn_js_1.default(buf, "le");
}
readU512() {
const buf = this.readBuffer(64);
return new bn_js_1.default(buf, "le");
}
readBuffer(len) {
if (this.offset + len > this.buf.length) throw new BorshError(`Expected buffer length ${len} isn't within bounds`);
const result = this.buf.slice(this.offset, this.offset + len);
this.offset += len;
return result;
}
readString() {
const len = this.readU32();
const buf = this.readBuffer(len);
try {
// NOTE: Using TextDecoder to fail on invalid UTF-8
return textDecoder.decode(buf);
} catch (e) {
throw new BorshError(`Error decoding UTF-8 string: ${e}`);
}
}
readFixedArray(len) {
return new Uint8Array(this.readBuffer(len));
}
readArray(fn) {
const len = this.readU32();
const result = Array();
for(let i = 0; i < len; ++i)result.push(fn());
return result;
}
}
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU8", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU16", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU32", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU64", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU128", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU256", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU512", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readString", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readFixedArray", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readArray", null);
exports.BinaryReader = BinaryReader;
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function serializeField(schema, fieldName, value, fieldType, writer) {
try {
// TODO: Handle missing values properly (make sure they never result in just skipped write)
if (typeof fieldType === "string") writer[`write${capitalizeFirstLetter(fieldType)}`](value);
else if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") {
if (value.length !== fieldType[0]) throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`);
writer.writeFixedArray(value);
} else if (fieldType.length === 2 && typeof fieldType[1] === "number") {
if (value.length !== fieldType[1]) throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`);
for(let i = 0; i < fieldType[1]; i++)serializeField(schema, null, value[i], fieldType[0], writer);
} else writer.writeArray(value, (item)=>{
serializeField(schema, fieldName, item, fieldType[0], writer);
});
} else if (fieldType.kind !== undefined) switch(fieldType.kind){
case "option":
if (value === null || value === undefined) writer.writeU8(0);
else {
writer.writeU8(1);
serializeField(schema, fieldName, value, fieldType.type, writer);
}
break;
default:
throw new BorshError(`FieldType ${fieldType} unrecognized`);
}
else serializeStruct(schema, value, writer);
} catch (error) {
if (error instanceof BorshError) error.addToFieldPath(fieldName);
throw error;
}
}
function serializeStruct(schema, obj, writer) {
if (typeof obj.borshSerialize === "function") {
obj.borshSerialize(writer);
return;
}
const structSchema = schema.get(obj.constructor);
if (!structSchema) throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);
if (structSchema.kind === "struct") structSchema.fields.map(([fieldName, fieldType])=>{
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
});
else if (structSchema.kind === "enum") {
const name = obj[structSchema.field];
for(let idx = 0; idx < structSchema.values.length; ++idx){
const [fieldName, fieldType] = structSchema.values[idx];
if (fieldName === name) {
writer.writeU8(idx);
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
break;
}
}
} else throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);
}
/// Serialize given object using schema of the form:
/// { class_name -> [ [field_name, field_type], .. ], .. }
function serialize(schema, obj, Writer = BinaryWriter) {
const writer = new Writer();
serializeStruct(schema, obj, writer);
return writer.toArray();
}
exports.serialize = serialize;
function deserializeField(schema, fieldName, fieldType, reader) {
try {
if (typeof fieldType === "string") return reader[`read${capitalizeFirstLetter(fieldType)}`]();
if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") return reader.readFixedArray(fieldType[0]);
else if (typeof fieldType[1] === "number") {
const arr = [];
for(let i = 0; i < fieldType[1]; i++)arr.push(deserializeField(schema, null, fieldType[0], reader));
return arr;
} else return reader.readArray(()=>deserializeField(schema, fieldName, fieldType[0], reader));
}
if (fieldType.kind === "option") {
const option = reader.readU8();
if (option) return deserializeField(schema, fieldName, fieldType.type, reader);
return undefined;
}
return deserializeStruct(schema, fieldType, reader);
} catch (error) {
if (error instanceof BorshError) error.addToFieldPath(fieldName);
throw error;
}
}
function deserializeStruct(schema, classType, reader) {
if (typeof classType.borshDeserialize === "function") return classType.borshDeserialize(reader);
const structSchema = schema.get(classType);
if (!structSchema) throw new BorshError(`Class ${classType.name} is missing in schema`);
if (structSchema.kind === "struct") {
const result = {};
for (const [fieldName, fieldType] of schema.get(classType).fields)result[fieldName] = deserializeField(schema, fieldName, fieldType, reader);
return new classType(result);
}
if (structSchema.kind === "enum") {
const idx = reader.readU8();
if (idx >= structSchema.values.length) throw new BorshError(`Enum index: ${idx} is out of range`);
const [fieldName1, fieldType1] = structSchema.values[idx];
const fieldValue = deserializeField(schema, fieldName1, fieldType1, reader);
return new classType({
[fieldName1]: fieldValue
});
}
throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`);
}
/// Deserializes object from bytes using schema.
function deserialize(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
const result = deserializeStruct(schema, classType, reader);
if (reader.offset < buffer.length) throw new BorshError(`Unexpected ${buffer.length - reader.offset} bytes after deserialized data`);
return result;
}
exports.deserialize = deserialize;
/// Deserializes object from bytes using schema, without checking the length read
function deserializeUnchecked(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
return deserializeStruct(schema, classType, reader);
}
exports.deserializeUnchecked = deserializeUnchecked;
},{"buffer":"dvCeB","bn.js":"VopIn","bs58":"4ji3p","text-encoding-utf-8":"feCA6"}],"dvCeB":[function(require,module,exports) {
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/ /* eslint-disable no-proto */ "use strict";
var base64 = require("base64-js");
var ieee754 = require("ieee754");
var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" // eslint-disable-line dot-notation
? Symbol["for"]("nodejs.util.inspect.custom") // eslint-disable-line dot-notation
: null;
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
var K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
function typedArraySupport() {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1);
var proto = {
foo: function() {
return 42;
}
};
Object.setPrototypeOf(proto, Uint8Array.prototype);
Object.setPrototypeOf(arr, proto);
return arr.foo() === 42;
} catch (e) {
return false;
}
}
Object.defineProperty(Buffer.prototype, "parent", {
enumerable: true,
get: function() {
if (!Buffer.isBuffer(this)) return undefined;
return this.buffer;
}
});
Object.defineProperty(Buffer.prototype, "offset", {
enumerable: true,
get: function() {
if (!Buffer.isBuffer(this)) return undefined;
return this.byteOffset;
}
});
function createBuffer(length) {
if (length > K_MAX_LENGTH) throw new RangeError('The value "' + length + '" is invalid for option "size"');
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/ function Buffer(arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === "number") {
if (typeof encodingOrOffset === "string") throw new TypeError('The "string" argument must be of type string. Received type number');
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
Buffer.poolSize = 8192 // not used by this implementation
;
function from(value, encodingOrOffset, length) {
if (typeof value === "string") return fromString(value, encodingOrOffset);
if (ArrayBuffer.isView(value)) return fromArrayView(value);
if (value == null) throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) return fromArrayBuffer(value, encodingOrOffset, length);
if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) return fromArrayBuffer(value, encodingOrOffset, length);
if (typeof value === "number") throw new TypeError('The "value" argument must not be of type number. Received type number');
var valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length);
var b = fromObject(value);
if (b) return b;
if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/ Buffer.from = function(value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
};
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(Buffer, Uint8Array);
function assertSize(size) {
if (typeof size !== "number") throw new TypeError('"size" argument must be of type number');
else if (size < 0) throw new RangeError('The value "' + size + '" is invalid for option "size"');
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) return createBuffer(size);
if (fill !== undefined) // Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpreted as a start offset.
return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
return createBuffer(size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/ Buffer.alloc = function(size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */ Buffer.allocUnsafe = function(size) {
return allocUnsafe(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/ Buffer.allocUnsafeSlow = function(size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== "string" || encoding === "") encoding = "utf8";
if (!Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
var length = byteLength(string, encoding) | 0;
var buf = createBuffer(length);
var actual = buf.write(string, encoding);
if (actual !== length) // Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual);
return buf;
}
function fromArrayLike(array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
var buf = createBuffer(length);
for(var i = 0; i < length; i += 1)buf[i] = array[i] & 255;
return buf;
}
function fromArrayView(arrayView) {
if (isInstance(arrayView, Uint8Array)) {
var copy = new Uint8Array(arrayView);
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
}
return fromArrayLike(arrayView);
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) throw new RangeError('"offset" is outside of buffer bounds');
if (array.byteLength < byteOffset + (length || 0)) throw new RangeError('"length" is outside of buffer bounds');
var buf;
if (byteOffset === undefined && length === undefined) buf = new Uint8Array(array);
else if (length === undefined) buf = new Uint8Array(array, byteOffset);
else buf = new Uint8Array(array, byteOffset, length);
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
function fromObject(obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
var buf = createBuffer(len);
if (buf.length === 0) return buf;
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj.length !== undefined) {
if (typeof obj.length !== "number" || numberIsNaN(obj.length)) return createBuffer(0);
return fromArrayLike(obj);
}
if (obj.type === "Buffer" && Array.isArray(obj.data)) return fromArrayLike(obj.data);
}
function checked(length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) length = 0;
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
;
};
Buffer.compare = function compare(a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
if (a === b) return 0;
var x = a.length;
var y = b.length;
for(var i = 0, len = Math.min(x, y); i < len; ++i)if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch(String(encoding).toLowerCase()){
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "latin1":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!Array.isArray(list)) throw new TypeError('"list" argument must be an Array of Buffers');
if (list.length === 0) return Buffer.alloc(0);
var i;
if (length === undefined) {
length = 0;
for(i = 0; i < list.length; ++i)length += list[i].length;
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for(i = 0; i < list.length; ++i){
var buf = list[i];
if (isInstance(buf, Uint8Array)) {
if (pos + buf.length > buffer.length) Buffer.from(buf).copy(buffer, pos);
else Uint8Array.prototype.set.call(buffer, buf, pos);
} else if (!Buffer.isBuffer(buf)) throw new TypeError('"list" argument must be an Array of Buffers');
else buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) return string.length;
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) return string.byteLength;
if (typeof string !== "string") throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
var len = string.length;
var mustMatch = arguments.length > 2 && arguments[2] === true;
if (!mustMatch && len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for(;;)switch(encoding){
case "ascii":
case "latin1":
case "binary":
return len;
case "utf8":
case "utf-8":
return utf8ToBytes(string).length;
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return len * 2;
case "hex":
return len >>> 1;
case "base64":
return base64ToBytes(string).length;
default:
if (loweredCase) return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
;
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) start = 0;
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) return "";
if (end === undefined || end > this.length) end = this.length;
if (end <= 0) return "";
// Force coercion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) return "";
if (!encoding) encoding = "utf8";
while(true)switch(encoding){
case "hex":
return hexSlice(this, start, end);
case "utf8":
case "utf-8":
return utf8Slice(this, start, end);
case "ascii":
return asciiSlice(this, start, end);
case "latin1":
case "binary":
return latin1Slice(this, start, end);
case "base64":
return base64Slice(this, start, end);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = (encoding + "").toLowerCase();
loweredCase = true;
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
for(var i = 0; i < len; i += 2)swap(this, i, i + 1);
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
for(var i = 0; i < len; i += 4){
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
for(var i = 0; i < len; i += 8){
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length;
if (length === 0) return "";
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.toLocaleString = Buffer.prototype.toString;
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = "";
var max = exports.INSPECT_MAX_BYTES;
str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
if (this.length > max) str += " ... ";
return "<Buffer " + str + ">";
};
if (customInspectSymbol) Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) target = Buffer.from(target, target.offset, target.byteLength);
if (!Buffer.isBuffer(target)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
if (start === undefined) start = 0;
if (end === undefined) end = target ? target.length : 0;
if (thisStart === undefined) thisStart = 0;
if (thisEnd === undefined) thisEnd = this.length;
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) throw new RangeError("out of range index");
if (thisStart >= thisEnd && start >= end) return 0;
if (thisStart >= thisEnd) return -1;
if (start >= end) return 1;
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for(var i = 0; i < len; ++i)if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === "string") {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff;
else if (byteOffset < -2147483648) byteOffset = -2147483648;
byteOffset = +byteOffset // Coerce to Number.
;
if (numberIsNaN(byteOffset)) // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;
else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1;
}
// Normalize val
if (typeof val === "string") val = Buffer.from(val, encoding);
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) return -1;
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === "number") {
val = val & 0xFF // Search for a byte value [0-255]
;
if (typeof Uint8Array.prototype.indexOf === "function") {
if (dir) return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
else return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
return arrayIndexOf(buffer, [
val
], byteOffset, encoding, dir);
}
throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
if (arr.length < 2 || val.length < 2) return -1;
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) return buf[i];
else return buf.readUInt16BE(i * indexSize);
}
var i;
if (dir) {
var foundIndex = -1;
for(i = byteOffset; i < arrLength; i++)if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for(i = byteOffset; i >= 0; i--){
var found = true;
for(var j = 0; j < valLength; j++)if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) length = remaining;
else {
length = Number(length);
if (length > remaining) length = remaining;
}
var strLen = string.length;
if (length > strLen / 2) length = strLen / 2;
for(var i = 0; i < length; ++i){
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = "utf8";
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === "string") {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === undefined) encoding = "utf8";
} else {
encoding = length;
length = undefined;
}
} else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) throw new RangeError("Attempt to write outside buffer bounds");
if (!encoding) encoding = "utf8";
var loweredCase = false;
for(;;)switch(encoding){
case "hex":
return hexWrite(this, string, offset, length);
case "utf8":
case "utf-8":
return utf8Write(this, string, offset, length);
case "ascii":
case "latin1":
case "binary":
return asciiWrite(this, string, offset, length);
case "base64":
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: "Buffer",
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) return base64.fromByteArray(buf);
else return base64.fromByteArray(buf.slice(start, end));
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while(i < end){
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch(bytesPerSequence){
case 1:
if (firstByte < 0x80) codePoint = firstByte;
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
if (tempCodePoint > 0x7F) codePoint = tempCodePoint;
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) codePoint = tempCodePoint;
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) codePoint = tempCodePoint;
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
;
// Decode in chunks to avoid "call stack size exceeded".
var res = "";
var i = 0;
while(i < len)res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
return res;
}
function asciiSlice(buf, start, end) {
var ret = "";
end = Math.min(buf.length, end);
for(var i = start; i < end; ++i)ret += String.fromCharCode(buf[i] & 0x7F);
return ret;
}
function latin1Slice(buf, start, end) {
var ret = "";
end = Math.min(buf.length, end);
for(var i = start; i < end; ++i)ret += String.fromCharCode(buf[i]);
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = "";
for(var i = start; i < end; ++i)out += hexSliceLookupTable[buf[i]];
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = "";
// If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
for(var i = 0; i < bytes.length - 1; i += 2)res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) start = len;
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) end = len;
if (end < start) end = start;
var newBuf = this.subarray(start, end);
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(newBuf, Buffer.prototype);
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/ function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
}
Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while(++i < byteLength && (mul *= 0x100))val += this[offset + i] * mul;
return val;
};
Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset + --byteLength];
var mul = 1;
while(byteLength > 0 && (mul *= 0x100))val += this[offset + --byteLength] * mul;
return val;
};
Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
};
Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while(++i < byteLength && (mul *= 0x100))val += this[offset + i] * mul;
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while(i > 0 && (mul *= 0x100))val += this[offset + --i] * mul;
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | this[offset + 1] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | this[offset] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError("Index out of range");
}
Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while(++i < byteLength && (mul *= 0x100))this[offset + i] = value / mul & 0xFF;
return offset + byteLength;
};
Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while(--i >= 0 && (mul *= 0x100))this[offset + i] = value / mul & 0xFF;
return offset + byteLength;
};
Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while(++i < byteLength && (mul *= 0x100)){
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) sub = 1;
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while(--i >= 0 && (mul *= 0x100)){
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) sub = 1;
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
if (value < 0) value = 0xffffffff + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError("Index out of range");
if (offset < 0) throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -340282346638528860000000000000000000000);
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError("argument should be a Buffer");
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) throw new RangeError("targetStart out of bounds");
if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
if (end < 0) throw new RangeError("sourceEnd out of bounds");
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) end = target.length - targetStart + start;
var len = end - start;
if (this === target && typeof Uint8Array.prototype.copyWithin === "function") // Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end);
else Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === "string") {
if (typeof start === "string") {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === "string") {
encoding = end;
end = this.length;
}
if (encoding !== undefined && typeof encoding !== "string") throw new TypeError("encoding must be a string");
if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
if (val.length === 1) {
var code = val.charCodeAt(0);
if (encoding === "utf8" && code < 128 || encoding === "latin1") // Fast path: If `val` fits into a single byte, use that numeric value.
val = code;
}
} else if (typeof val === "number") val = val & 255;
else if (typeof val === "boolean") val = Number(val);
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) throw new RangeError("Out of range index");
if (end <= start) return this;
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === "number") for(i = start; i < end; ++i)this[i] = val;
else {
var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
var len = bytes.length;
if (len === 0) throw new TypeError('The value "' + val + '" is invalid for argument "value"');
for(i = 0; i < end - start; ++i)this[i + start] = bytes[i % len];
}
return this;
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split("=")[0];
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, "");
// Node converts strings with length < 2 to ''
if (str.length < 2) return "";
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while(str.length % 4 !== 0)str = str + "=";
return str;
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for(var i = 0; i < length; ++i){
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) // valid bmp char, but last char was a lead
{
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else throw new Error("Invalid code point");
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for(var i = 0; i < str.length; ++i)// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for(var i = 0; i < str.length; ++i){
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
for(var i = 0; i < length; ++i){
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance(obj, type) {
return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
}
function numberIsNaN(obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
;
}
// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
var hexSliceLookupTable = function() {
var alphabet = "0123456789abcdef";
var table = new Array(256);
for(var i = 0; i < 16; ++i){
var i16 = i * 16;
for(var j = 0; j < 16; ++j)table[i16 + j] = alphabet[i] + alphabet[j];
}
return table;
}();
},{"base64-js":"5AK51","ieee754":"5UtKn"}],"5AK51":[function(require,module,exports) {
"use strict";
exports.byteLength = byteLength;
exports.toByteArray = toByteArray;
exports.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for(var i = 0, len = code.length; i < len; ++i){
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
var len = b64.length;
if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf("=");
if (validLen === -1) validLen = len;
var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
return [
validLen,
placeHoldersLen
];
}
// base64 is 4/3 + up to two characters of the original data
function byteLength(b64) {
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
var tmp;
var lens = getLens(b64);
var validLen = lens[0];
var placeHoldersLen = lens[1];
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
var curByte = 0;
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
var i;
for(i = 0; i < len; i += 4){
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = tmp >> 16 & 0xFF;
arr[curByte++] = tmp >> 8 & 0xFF;
arr[curByte++] = tmp & 0xFF;
}
if (placeHoldersLen === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[curByte++] = tmp & 0xFF;
}
if (placeHoldersLen === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[curByte++] = tmp >> 8 & 0xFF;
arr[curByte++] = tmp & 0xFF;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for(var i = start; i < end; i += 3){
tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
output.push(tripletToBase64(tmp));
}
return output.join("");
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
;
var parts = [];
var maxChunkLength = 16383 // must be multiple of 3
;
// go through the array every three bytes, we'll deal with trailing stuff later
for(var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength)parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + "==");
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + "=");
}
return parts.join("");
}
},{}],"5UtKn":[function(require,module,exports) {
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for(; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) e = 1 - eBias;
else if (e === eMax) return m ? NaN : (s ? -1 : 1) * Infinity;
else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) value += rt / c;
else value += rt * Math.pow(2, 1 - eBias);
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],"VopIn":[function(require,module,exports) {
(function(module1, exports) {
"use strict";
// Utils
function assert(val, msg) {
if (!val) throw new Error(msg || "Assertion failed");
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function() {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN(number, base, endian) {
if (BN.isBN(number)) return number;
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === "le" || base === "be") {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || "be");
}
}
if (typeof module1 === "object") module1.exports = BN;
else exports.BN = BN;
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") Buffer = window.Buffer;
else Buffer = require("buffer").Buffer;
} catch (e) {}
BN.isBN = function isBN(num) {
if (num instanceof BN) return true;
return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max(left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min(left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init(number, base, endian) {
if (typeof number === "number") return this._initNumber(number, base, endian);
if (typeof number === "object") return this._initArray(number, base, endian);
if (base === "hex") base = 16;
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, "");
var start = 0;
if (number[0] === "-") {
start++;
this.negative = 1;
}
if (start < number.length) {
if (base === 16) this._parseHex(number, start, endian);
else {
this._parseBase(number, base, start);
if (endian === "le") this._initArray(this.toArray(), base, endian);
}
}
};
BN.prototype._initNumber = function _initNumber(number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [
number & 0x3ffffff
];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
number / 0x4000000 & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
number / 0x4000000 & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== "le") return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray(number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === "number");
if (number.length <= 0) {
this.words = [
0
];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for(var i = 0; i < this.length; i++)this.words[i] = 0;
var j, w;
var off = 0;
if (endian === "be") for(i = number.length - 1, j = 0; i >= 0; i -= 3){
w = number[i] | number[i - 1] << 8 | number[i - 2] << 16;
this.words[j] |= w << off & 0x3ffffff;
this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
else if (endian === "le") for(i = 0, j = 0; i < number.length; i += 3){
w = number[i] | number[i + 1] << 8 | number[i + 2] << 16;
this.words[j] |= w << off & 0x3ffffff;
this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
return this._strip();
};
function parseHex4Bits(string, index) {
var c = string.charCodeAt(index);
// '0' - '9'
if (c >= 48 && c <= 57) return c - 48;
else if (c >= 65 && c <= 70) return c - 55;
else if (c >= 97 && c <= 102) return c - 87;
else assert(false, "Invalid character in " + string);
}
function parseHexByte(string, lowerBound, index) {
var r = parseHex4Bits(string, index);
if (index - 1 >= lowerBound) r |= parseHex4Bits(string, index - 1) << 4;
return r;
}
BN.prototype._parseHex = function _parseHex(number, start, endian) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for(var i = 0; i < this.length; i++)this.words[i] = 0;
// 24-bits chunks
var off = 0;
var j = 0;
var w;
if (endian === "be") for(i = number.length - 1; i >= start; i -= 2){
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else off += 8;
}
else {
var parseLength = number.length - start;
for(i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2){
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else off += 8;
}
}
this._strip();
};
function parseBase(str, start, end, mul) {
var r = 0;
var b = 0;
var len = Math.min(str.length, end);
for(var i = start; i < len; i++){
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) b = c - 49 + 0xa;
else if (c >= 17) b = c - 17 + 0xa;
else b = c;
assert(c >= 0 && b < mul, "Invalid character");
r += b;
}
return r;
}
BN.prototype._parseBase = function _parseBase(number, base, start) {
// Initialize as zero
this.words = [
0
];
this.length = 1;
// Find length of limb in base
for(var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)limbLen++;
limbLen--;
limbPow = limbPow / base | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for(var i = start; i < end; i += limbLen){
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) this.words[0] += word;
else this._iaddn(word);
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for(i = 0; i < mod; i++)pow *= base;
this.imuln(pow);
if (this.words[0] + word < 0x4000000) this.words[0] += word;
else this._iaddn(word);
}
this._strip();
};
BN.prototype.copy = function copy(dest) {
dest.words = new Array(this.length);
for(var i = 0; i < this.length; i++)dest.words[i] = this.words[i];
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
function move(dest, src) {
dest.words = src.words;
dest.length = src.length;
dest.negative = src.negative;
dest.red = src.red;
}
BN.prototype._move = function _move(dest) {
move(dest, this);
};
BN.prototype.clone = function clone() {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand(size) {
while(this.length < size)this.words[this.length++] = 0;
return this;
};
// Remove leading `0` from `this`
BN.prototype._strip = function strip() {
while(this.length > 1 && this.words[this.length - 1] === 0)this.length--;
return this._normSign();
};
BN.prototype._normSign = function _normSign() {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) this.negative = 0;
return this;
};
// Check Symbol.for because not everywhere where Symbol defined
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") try {
BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect;
} catch (e1) {
BN.prototype.inspect = inspect;
}
else BN.prototype.inspect = inspect;
function inspect() {
return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
}
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/ var zeros = [
"",
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
"00000000",
"000000000",
"0000000000",
"00000000000",
"000000000000",
"0000000000000",
"00000000000000",
"000000000000000",
"0000000000000000",
"00000000000000000",
"000000000000000000",
"0000000000000000000",
"00000000000000000000",
"000000000000000000000",
"0000000000000000000000",
"00000000000000000000000",
"000000000000000000000000",
"0000000000000000000000000"
];
var groupSizes = [
0,
0,
25,
16,
12,
11,
10,
9,
8,
8,
7,
7,
7,
7,
6,
6,
6,
6,
6,
6,
6,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5
];
var groupBases = [
0,
0,
33554432,
43046721,
16777216,
48828125,
60466176,
40353607,
16777216,
43046721,
10000000,
19487171,
35831808,
62748517,
7529536,
11390625,
16777216,
24137569,
34012224,
47045881,
64000000,
4084101,
5153632,
6436343,
7962624,
9765625,
11881376,
14348907,
17210368,
20511149,
24300000,
28629151,
33554432,
39135393,
45435424,
52521875,
60466176
];
BN.prototype.toString = function toString(base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === "hex") {
out = "";
var off = 0;
var carry = 0;
for(var i = 0; i < this.length; i++){
var w = this.words[i];
var word = ((w << off | carry) & 0xffffff).toString(16);
carry = w >>> 24 - off & 0xffffff;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
if (carry !== 0 || i !== this.length - 1) out = zeros[6 - word.length] + word + out;
else out = word + out;
}
if (carry !== 0) out = carry.toString(16) + out;
while(out.length % padding !== 0)out = "0" + out;
if (this.negative !== 0) out = "-" + out;
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = "";
var c = this.clone();
c.negative = 0;
while(!c.isZero()){
var r = c.modrn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) out = zeros[groupSize - r.length] + r + out;
else out = r + out;
}
if (this.isZero()) out = "0" + out;
while(out.length % padding !== 0)out = "0" + out;
if (this.negative !== 0) out = "-" + out;
return out;
}
assert(false, "Base should be between 2 and 36");
};
BN.prototype.toNumber = function toNumber() {
var ret = this.words[0];
if (this.length === 2) ret += this.words[1] * 0x4000000;
else if (this.length === 3 && this.words[2] === 0x01) // NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + this.words[1] * 0x4000000;
else if (this.length > 2) assert(false, "Number can only safely store up to 53 bits");
return this.negative !== 0 ? -ret : ret;
};
BN.prototype.toJSON = function toJSON() {
return this.toString(16, 2);
};
if (Buffer) BN.prototype.toBuffer = function toBuffer(endian, length) {
return this.toArrayLike(Buffer, endian, length);
};
BN.prototype.toArray = function toArray(endian, length) {
return this.toArrayLike(Array, endian, length);
};
var allocate = function allocate(ArrayType, size) {
if (ArrayType.allocUnsafe) return ArrayType.allocUnsafe(size);
return new ArrayType(size);
};
BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
this._strip();
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, "byte array longer than desired length");
assert(reqLength > 0, "Requested array length <= 0");
var res = allocate(ArrayType, reqLength);
var postfix = endian === "le" ? "LE" : "BE";
this["_toArrayLike" + postfix](res, byteLength);
return res;
};
BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) {
var position = 0;
var carry = 0;
for(var i = 0, shift = 0; i < this.length; i++){
var word = this.words[i] << shift | carry;
res[position++] = word & 0xff;
if (position < res.length) res[position++] = word >> 8 & 0xff;
if (position < res.length) res[position++] = word >> 16 & 0xff;
if (shift === 6) {
if (position < res.length) res[position++] = word >> 24 & 0xff;
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position < res.length) {
res[position++] = carry;
while(position < res.length)res[position++] = 0;
}
};
BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) {
var position = res.length - 1;
var carry = 0;
for(var i = 0, shift = 0; i < this.length; i++){
var word = this.words[i] << shift | carry;
res[position--] = word & 0xff;
if (position >= 0) res[position--] = word >> 8 & 0xff;
if (position >= 0) res[position--] = word >> 16 & 0xff;
if (shift === 6) {
if (position >= 0) res[position--] = word >> 24 & 0xff;
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position >= 0) {
res[position--] = carry;
while(position >= 0)res[position--] = 0;
}
};
if (Math.clz32) BN.prototype._countBits = function _countBits(w) {
return 32 - Math.clz32(w);
};
else BN.prototype._countBits = function _countBits(w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
BN.prototype._zeroBits = function _zeroBits(w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) r++;
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength() {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray(num) {
var w = new Array(num.bitLength());
for(var bit = 0; bit < w.length; bit++){
var off = bit / 26 | 0;
var wbit = bit % 26;
w[bit] = num.words[off] >>> wbit & 0x01;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits() {
if (this.isZero()) return 0;
var r = 0;
for(var i = 0; i < this.length; i++){
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength() {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos(width) {
if (this.negative !== 0) return this.abs().inotn(width).iaddn(1);
return this.clone();
};
BN.prototype.fromTwos = function fromTwos(width) {
if (this.testn(width - 1)) return this.notn(width).iaddn(1).ineg();
return this.clone();
};
BN.prototype.isNeg = function isNeg() {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg() {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg() {
if (!this.isZero()) this.negative ^= 1;
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor(num) {
while(this.length < num.length)this.words[this.length++] = 0;
for(var i = 0; i < num.length; i++)this.words[i] = this.words[i] | num.words[i];
return this._strip();
};
BN.prototype.ior = function ior(num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or(num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor(num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand(num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) b = num;
else b = this;
for(var i = 0; i < b.length; i++)this.words[i] = this.words[i] & num.words[i];
this.length = b.length;
return this._strip();
};
BN.prototype.iand = function iand(num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and(num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand(num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor(num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for(var i = 0; i < b.length; i++)this.words[i] = a.words[i] ^ b.words[i];
if (this !== a) for(; i < a.length; i++)this.words[i] = a.words[i];
this.length = a.length;
return this._strip();
};
BN.prototype.ixor = function ixor(num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor(num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor(num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn(width) {
assert(typeof width === "number" && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) bytesNeeded--;
// Handle complete words
for(var i = 0; i < bytesNeeded; i++)this.words[i] = ~this.words[i] & 0x3ffffff;
// Handle the residue
if (bitsLeft > 0) this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft;
// And remove leading zeroes
return this._strip();
};
BN.prototype.notn = function notn(width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn(bit, val) {
assert(typeof bit === "number" && bit >= 0);
var off = bit / 26 | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) this.words[off] = this.words[off] | 1 << wbit;
else this.words[off] = this.words[off] & ~(1 << wbit);
return this._strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd(num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for(var i = 0; i < b.length; i++){
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for(; carry !== 0 && i < a.length; i++){
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) for(; i < a.length; i++)this.words[i] = a.words[i];
return this;
};
// Add `num` to `this`
BN.prototype.add = function add(num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub(num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for(var i = 0; i < b.length; i++){
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for(; carry !== 0 && i < a.length; i++){
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) for(; i < a.length; i++)this.words[i] = a.words[i];
this.length = Math.max(this.length, i);
if (a !== this) this.negative = 1;
return this._strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub(num) {
return this.clone().isub(num);
};
function smallMulTo(self, num, out) {
out.negative = num.negative ^ self.negative;
var len = self.length + num.length | 0;
out.length = len;
len = len - 1 | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = r / 0x4000000 | 0;
out.words[0] = lo;
for(var k = 1; k < len; k++){
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for(var j = Math.max(0, k - self.length + 1); j <= maxJ; j++){
var i = k - j | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += r / 0x4000000 | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) out.words[k] = carry | 0;
else out.length--;
return out._strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo(self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */ lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = mid + Math.imul(ah0, bl0) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
w0 &= 0x3ffffff;
/* k = 1 */ lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = mid + Math.imul(ah1, bl0) | 0;
hi = Math.imul(ah1, bh0);
lo = lo + Math.imul(al0, bl1) | 0;
mid = mid + Math.imul(al0, bh1) | 0;
mid = mid + Math.imul(ah0, bl1) | 0;
hi = hi + Math.imul(ah0, bh1) | 0;
var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
w1 &= 0x3ffffff;
/* k = 2 */ lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = mid + Math.imul(ah2, bl0) | 0;
hi = Math.imul(ah2, bh0);
lo = lo + Math.imul(al1, bl1) | 0;
mid = mid + Math.imul(al1, bh1) | 0;
mid = mid + Math.imul(ah1, bl1) | 0;
hi = hi + Math.imul(ah1, bh1) | 0;
lo = lo + Math.imul(al0, bl2) | 0;
mid = mid + Math.imul(al0, bh2) | 0;
mid = mid + Math.imul(ah0, bl2) | 0;
hi = hi + Math.imul(ah0, bh2) | 0;
var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
w2 &= 0x3ffffff;
/* k = 3 */ lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = mid + Math.imul(ah3, bl0) | 0;
hi = Math.imul(ah3, bh0);
lo = lo + Math.imul(al2, bl1) | 0;
mid = mid + Math.imul(al2, bh1) | 0;
mid = mid + Math.imul(ah2, bl1) | 0;
hi = hi + Math.imul(ah2, bh1) | 0;
lo = lo + Math.imul(al1, bl2) | 0;
mid = mid + Math.imul(al1, bh2) | 0;
mid = mid + Math.imul(ah1, bl2) | 0;
hi = hi + Math.imul(ah1, bh2) | 0;
lo = lo + Math.imul(al0, bl3) | 0;
mid = mid + Math.imul(al0, bh3) | 0;
mid = mid + Math.imul(ah0, bl3) | 0;
hi = hi + Math.imul(ah0, bh3) | 0;
var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
w3 &= 0x3ffffff;
/* k = 4 */ lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = mid + Math.imul(ah4, bl0) | 0;
hi = Math.imul(ah4, bh0);
lo = lo + Math.imul(al3, bl1) | 0;
mid = mid + Math.imul(al3, bh1) | 0;
mid = mid + Math.imul(ah3, bl1) | 0;
hi = hi + Math.imul(ah3, bh1) | 0;
lo = lo + Math.imul(al2, bl2) | 0;
mid = mid + Math.imul(al2, bh2) | 0;
mid = mid + Math.imul(ah2, bl2) | 0;
hi = hi + Math.imul(ah2, bh2) | 0;
lo = lo + Math.imul(al1, bl3) | 0;
mid = mid + Math.imul(al1, bh3) | 0;
mid = mid + Math.imul(ah1, bl3) | 0;
hi = hi + Math.imul(ah1, bh3) | 0;
lo = lo + Math.imul(al0, bl4) | 0;
mid = mid + Math.imul(al0, bh4) | 0;
mid = mid + Math.imul(ah0, bl4) | 0;
hi = hi + Math.imul(ah0, bh4) | 0;
var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
w4 &= 0x3ffffff;
/* k = 5 */ lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = mid + Math.imul(ah5, bl0) | 0;
hi = Math.imul(ah5, bh0);
lo = lo + Math.imul(al4, bl1) | 0;
mid = mid + Math.imul(al4, bh1) | 0;
mid = mid + Math.imul(ah4, bl1) | 0;
hi = hi + Math.imul(ah4, bh1) | 0;
lo = lo + Math.imul(al3, bl2) | 0;
mid = mid + Math.imul(al3, bh2) | 0;
mid = mid + Math.imul(ah3, bl2) | 0;
hi = hi + Math.imul(ah3, bh2) | 0;
lo = lo + Math.imul(al2, bl3) | 0;
mid = mid + Math.imul(al2, bh3) | 0;
mid = mid + Math.imul(ah2, bl3) | 0;
hi = hi + Math.imul(ah2, bh3) | 0;
lo = lo + Math.imul(al1, bl4) | 0;
mid = mid + Math.imul(al1, bh4) | 0;
mid = mid + Math.imul(ah1, bl4) | 0;
hi = hi + Math.imul(ah1, bh4) | 0;
lo = lo + Math.imul(al0, bl5) | 0;
mid = mid + Math.imul(al0, bh5) | 0;
mid = mid + Math.imul(ah0, bl5) | 0;
hi = hi + Math.imul(ah0, bh5) | 0;
var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
w5 &= 0x3ffffff;
/* k = 6 */ lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = mid + Math.imul(ah6, bl0) | 0;
hi = Math.imul(ah6, bh0);
lo = lo + Math.imul(al5, bl1) | 0;
mid = mid + Math.imul(al5, bh1) | 0;
mid = mid + Math.imul(ah5, bl1) | 0;
hi = hi + Math.imul(ah5, bh1) | 0;
lo = lo + Math.imul(al4, bl2) | 0;
mid = mid + Math.imul(al4, bh2) | 0;
mid = mid + Math.imul(ah4, bl2) | 0;
hi = hi + Math.imul(ah4, bh2) | 0;
lo = lo + Math.imul(al3, bl3) | 0;
mid = mid + Math.imul(al3, bh3) | 0;
mid = mid + Math.imul(ah3, bl3) | 0;
hi = hi + Math.imul(ah3, bh3) | 0;
lo = lo + Math.imul(al2, bl4) | 0;
mid = mid + Math.imul(al2, bh4) | 0;
mid = mid + Math.imul(ah2, bl4) | 0;
hi = hi + Math.imul(ah2, bh4) | 0;
lo = lo + Math.imul(al1, bl5) | 0;
mid = mid + Math.imul(al1, bh5) | 0;
mid = mid + Math.imul(ah1, bl5) | 0;
hi = hi + Math.imul(ah1, bh5) | 0;
lo = lo + Math.imul(al0, bl6) | 0;
mid = mid + Math.imul(al0, bh6) | 0;
mid = mid + Math.imul(ah0, bl6) | 0;
hi = hi + Math.imul(ah0, bh6) | 0;
var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
w6 &= 0x3ffffff;
/* k = 7 */ lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = mid + Math.imul(ah7, bl0) | 0;
hi = Math.imul(ah7, bh0);
lo = lo + Math.imul(al6, bl1) | 0;
mid = mid + Math.imul(al6, bh1) | 0;
mid = mid + Math.imul(ah6, bl1) | 0;
hi = hi + Math.imul(ah6, bh1) | 0;
lo = lo + Math.imul(al5, bl2) | 0;
mid = mid + Math.imul(al5, bh2) | 0;
mid = mid + Math.imul(ah5, bl2) | 0;
hi = hi + Math.imul(ah5, bh2) | 0;
lo = lo + Math.imul(al4, bl3) | 0;
mid = mid + Math.imul(al4, bh3) | 0;
mid = mid + Math.imul(ah4, bl3) | 0;
hi = hi + Math.imul(ah4, bh3) | 0;
lo = lo + Math.imul(al3, bl4) | 0;
mid = mid + Math.imul(al3, bh4) | 0;
mid = mid + Math.imul(ah3, bl4) | 0;
hi = hi + Math.imul(ah3, bh4) | 0;
lo = lo + Math.imul(al2, bl5) | 0;
mid = mid + Math.imul(al2, bh5) | 0;
mid = mid + Math.imul(ah2, bl5) | 0;
hi = hi + Math.imul(ah2, bh5) | 0;
lo = lo + Math.imul(al1, bl6) | 0;
mid = mid + Math.imul(al1, bh6) | 0;
mid = mid + Math.imul(ah1, bl6) | 0;
hi = hi + Math.imul(ah1, bh6) | 0;
lo = lo + Math.imul(al0, bl7) | 0;
mid = mid + Math.imul(al0, bh7) | 0;
mid = mid + Math.imul(ah0, bl7) | 0;
hi = hi + Math.imul(ah0, bh7) | 0;
var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
w7 &= 0x3ffffff;
/* k = 8 */ lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = mid + Math.imul(ah8, bl0) | 0;
hi = Math.imul(ah8, bh0);
lo = lo + Math.imul(al7, bl1) | 0;
mid = mid + Math.imul(al7, bh1) | 0;
mid = mid + Math.imul(ah7, bl1) | 0;
hi = hi + Math.imul(ah7, bh1) | 0;
lo = lo + Math.imul(al6, bl2) | 0;
mid = mid + Math.imul(al6, bh2) | 0;
mid = mid + Math.imul(ah6, bl2) | 0;
hi = hi + Math.imul(ah6, bh2) | 0;
lo = lo + Math.imul(al5, bl3) | 0;
mid = mid + Math.imul(al5, bh3) | 0;
mid = mid + Math.imul(ah5, bl3) | 0;
hi = hi + Math.imul(ah5, bh3) | 0;
lo = lo + Math.imul(al4, bl4) | 0;
mid = mid + Math.imul(al4, bh4) | 0;
mid = mid + Math.imul(ah4, bl4) | 0;
hi = hi + Math.imul(ah4, bh4) | 0;
lo = lo + Math.imul(al3, bl5) | 0;
mid = mid + Math.imul(al3, bh5) | 0;
mid = mid + Math.imul(ah3, bl5) | 0;
hi = hi + Math.imul(ah3, bh5) | 0;
lo = lo + Math.imul(al2, bl6) | 0;
mid = mid + Math.imul(al2, bh6) | 0;
mid = mid + Math.imul(ah2, bl6) | 0;
hi = hi + Math.imul(ah2, bh6) | 0;
lo = lo + Math.imul(al1, bl7) | 0;
mid = mid + Math.imul(al1, bh7) | 0;
mid = mid + Math.imul(ah1, bl7) | 0;
hi = hi + Math.imul(ah1, bh7) | 0;
lo = lo + Math.imul(al0, bl8) | 0;
mid = mid + Math.imul(al0, bh8) | 0;
mid = mid + Math.imul(ah0, bl8) | 0;
hi = hi + Math.imul(ah0, bh8) | 0;
var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
w8 &= 0x3ffffff;
/* k = 9 */ lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = mid + Math.imul(ah9, bl0) | 0;
hi = Math.imul(ah9, bh0);
lo = lo + Math.imul(al8, bl1) | 0;
mid = mid + Math.imul(al8, bh1) | 0;
mid = mid + Math.imul(ah8, bl1) | 0;
hi = hi + Math.imul(ah8, bh1) | 0;
lo = lo + Math.imul(al7, bl2) | 0;
mid = mid + Math.imul(al7, bh2) | 0;
mid = mid + Math.imul(ah7, bl2) | 0;
hi = hi + Math.imul(ah7, bh2) | 0;
lo = lo + Math.imul(al6, bl3) | 0;
mid = mid + Math.imul(al6, bh3) | 0;
mid = mid + Math.imul(ah6, bl3) | 0;
hi = hi + Math.imul(ah6, bh3) | 0;
lo = lo + Math.imul(al5, bl4) | 0;
mid = mid + Math.imul(al5, bh4) | 0;
mid = mid + Math.imul(ah5, bl4) | 0;
hi = hi + Math.imul(ah5, bh4) | 0;
lo = lo + Math.imul(al4, bl5) | 0;
mid = mid + Math.imul(al4, bh5) | 0;
mid = mid + Math.imul(ah4, bl5) | 0;
hi = hi + Math.imul(ah4, bh5) | 0;
lo = lo + Math.imul(al3, bl6) | 0;
mid = mid + Math.imul(al3, bh6) | 0;
mid = mid + Math.imul(ah3, bl6) | 0;
hi = hi + Math.imul(ah3, bh6) | 0;
lo = lo + Math.imul(al2, bl7) | 0;
mid = mid + Math.imul(al2, bh7) | 0;
mid = mid + Math.imul(ah2, bl7) | 0;
hi = hi + Math.imul(ah2, bh7) | 0;
lo = lo + Math.imul(al1, bl8) | 0;
mid = mid + Math.imul(al1, bh8) | 0;
mid = mid + Math.imul(ah1, bl8) | 0;
hi = hi + Math.imul(ah1, bh8) | 0;
lo = lo + Math.imul(al0, bl9) | 0;
mid = mid + Math.imul(al0, bh9) | 0;
mid = mid + Math.imul(ah0, bl9) | 0;
hi = hi + Math.imul(ah0, bh9) | 0;
var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
w9 &= 0x3ffffff;
/* k = 10 */ lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = mid + Math.imul(ah9, bl1) | 0;
hi = Math.imul(ah9, bh1);
lo = lo + Math.imul(al8, bl2) | 0;
mid = mid + Math.imul(al8, bh2) | 0;
mid = mid + Math.imul(ah8, bl2) | 0;
hi = hi + Math.imul(ah8, bh2) | 0;
lo = lo + Math.imul(al7, bl3) | 0;
mid = mid + Math.imul(al7, bh3) | 0;
mid = mid + Math.imul(ah7, bl3) | 0;
hi = hi + Math.imul(ah7, bh3) | 0;
lo = lo + Math.imul(al6, bl4) | 0;
mid = mid + Math.imul(al6, bh4) | 0;
mid = mid + Math.imul(ah6, bl4) | 0;
hi = hi + Math.imul(ah6, bh4) | 0;
lo = lo + Math.imul(al5, bl5) | 0;
mid = mid + Math.imul(al5, bh5) | 0;
mid = mid + Math.imul(ah5, bl5) | 0;
hi = hi + Math.imul(ah5, bh5) | 0;
lo = lo + Math.imul(al4, bl6) | 0;
mid = mid + Math.imul(al4, bh6) | 0;
mid = mid + Math.imul(ah4, bl6) | 0;
hi = hi + Math.imul(ah4, bh6) | 0;
lo = lo + Math.imul(al3, bl7) | 0;
mid = mid + Math.imul(al3, bh7) | 0;
mid = mid + Math.imul(ah3, bl7) | 0;
hi = hi + Math.imul(ah3, bh7) | 0;
lo = lo + Math.imul(al2, bl8) | 0;
mid = mid + Math.imul(al2, bh8) | 0;
mid = mid + Math.imul(ah2, bl8) | 0;
hi = hi + Math.imul(ah2, bh8) | 0;
lo = lo + Math.imul(al1, bl9) | 0;
mid = mid + Math.imul(al1, bh9) | 0;
mid = mid + Math.imul(ah1, bl9) | 0;
hi = hi + Math.imul(ah1, bh9) | 0;
var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
w10 &= 0x3ffffff;
/* k = 11 */ lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = mid + Math.imul(ah9, bl2) | 0;
hi = Math.imul(ah9, bh2);
lo = lo + Math.imul(al8, bl3) | 0;
mid = mid + Math.imul(al8, bh3) | 0;
mid = mid + Math.imul(ah8, bl3) | 0;
hi = hi + Math.imul(ah8, bh3) | 0;
lo = lo + Math.imul(al7, bl4) | 0;
mid = mid + Math.imul(al7, bh4) | 0;
mid = mid + Math.imul(ah7, bl4) | 0;
hi = hi + Math.imul(ah7, bh4) | 0;
lo = lo + Math.imul(al6, bl5) | 0;
mid = mid + Math.imul(al6, bh5) | 0;
mid = mid + Math.imul(ah6, bl5) | 0;
hi = hi + Math.imul(ah6, bh5) | 0;
lo = lo + Math.imul(al5, bl6) | 0;
mid = mid + Math.imul(al5, bh6) | 0;
mid = mid + Math.imul(ah5, bl6) | 0;
hi = hi + Math.imul(ah5, bh6) | 0;
lo = lo + Math.imul(al4, bl7) | 0;
mid = mid + Math.imul(al4, bh7) | 0;
mid = mid + Math.imul(ah4, bl7) | 0;
hi = hi + Math.imul(ah4, bh7) | 0;
lo = lo + Math.imul(al3, bl8) | 0;
mid = mid + Math.imul(al3, bh8) | 0;
mid = mid + Math.imul(ah3, bl8) | 0;
hi = hi + Math.imul(ah3, bh8) | 0;
lo = lo + Math.imul(al2, bl9) | 0;
mid = mid + Math.imul(al2, bh9) | 0;
mid = mid + Math.imul(ah2, bl9) | 0;
hi = hi + Math.imul(ah2, bh9) | 0;
var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
w11 &= 0x3ffffff;
/* k = 12 */ lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = mid + Math.imul(ah9, bl3) | 0;
hi = Math.imul(ah9, bh3);
lo = lo + Math.imul(al8, bl4) | 0;
mid = mid + Math.imul(al8, bh4) | 0;
mid = mid + Math.imul(ah8, bl4) | 0;
hi = hi + Math.imul(ah8, bh4) | 0;
lo = lo + Math.imul(al7, bl5) | 0;
mid = mid + Math.imul(al7, bh5) | 0;
mid = mid + Math.imul(ah7, bl5) | 0;
hi = hi + Math.imul(ah7, bh5) | 0;
lo = lo + Math.imul(al6, bl6) | 0;
mid = mid + Math.imul(al6, bh6) | 0;
mid = mid + Math.imul(ah6, bl6) | 0;
hi = hi + Math.imul(ah6, bh6) | 0;
lo = lo + Math.imul(al5, bl7) | 0;
mid = mid + Math.imul(al5, bh7) | 0;
mid = mid + Math.imul(ah5, bl7) | 0;
hi = hi + Math.imul(ah5, bh7) | 0;
lo = lo + Math.imul(al4, bl8) | 0;
mid = mid + Math.imul(al4, bh8) | 0;
mid = mid + Math.imul(ah4, bl8) | 0;
hi = hi + Math.imul(ah4, bh8) | 0;
lo = lo + Math.imul(al3, bl9) | 0;
mid = mid + Math.imul(al3, bh9) | 0;
mid = mid + Math.imul(ah3, bl9) | 0;
hi = hi + Math.imul(ah3, bh9) | 0;
var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
w12 &= 0x3ffffff;
/* k = 13 */ lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = mid + Math.imul(ah9, bl4) | 0;
hi = Math.imul(ah9, bh4);
lo = lo + Math.imul(al8, bl5) | 0;
mid = mid + Math.imul(al8, bh5) | 0;
mid = mid + Math.imul(ah8, bl5) | 0;
hi = hi + Math.imul(ah8, bh5) | 0;
lo = lo + Math.imul(al7, bl6) | 0;
mid = mid + Math.imul(al7, bh6) | 0;
mid = mid + Math.imul(ah7, bl6) | 0;
hi = hi + Math.imul(ah7, bh6) | 0;
lo = lo + Math.imul(al6, bl7) | 0;
mid = mid + Math.imul(al6, bh7) | 0;
mid = mid + Math.imul(ah6, bl7) | 0;
hi = hi + Math.imul(ah6, bh7) | 0;
lo = lo + Math.imul(al5, bl8) | 0;
mid = mid + Math.imul(al5, bh8) | 0;
mid = mid + Math.imul(ah5, bl8) | 0;
hi = hi + Math.imul(ah5, bh8) | 0;
lo = lo + Math.imul(al4, bl9) | 0;
mid = mid + Math.imul(al4, bh9) | 0;
mid = mid + Math.imul(ah4, bl9) | 0;
hi = hi + Math.imul(ah4, bh9) | 0;
var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
w13 &= 0x3ffffff;
/* k = 14 */ lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = mid + Math.imul(ah9, bl5) | 0;
hi = Math.imul(ah9, bh5);
lo = lo + Math.imul(al8, bl6) | 0;
mid = mid + Math.imul(al8, bh6) | 0;
mid = mid + Math.imul(ah8, bl6) | 0;
hi = hi + Math.imul(ah8, bh6) | 0;
lo = lo + Math.imul(al7, bl7) | 0;
mid = mid + Math.imul(al7, bh7) | 0;
mid = mid + Math.imul(ah7, bl7) | 0;
hi = hi + Math.imul(ah7, bh7) | 0;
lo = lo + Math.imul(al6, bl8) | 0;
mid = mid + Math.imul(al6, bh8) | 0;
mid = mid + Math.imul(ah6, bl8) | 0;
hi = hi + Math.imul(ah6, bh8) | 0;
lo = lo + Math.imul(al5, bl9) | 0;
mid = mid + Math.imul(al5, bh9) | 0;
mid = mid + Math.imul(ah5, bl9) | 0;
hi = hi + Math.imul(ah5, bh9) | 0;
var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
w14 &= 0x3ffffff;
/* k = 15 */ lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = mid + Math.imul(ah9, bl6) | 0;
hi = Math.imul(ah9, bh6);
lo = lo + Math.imul(al8, bl7) | 0;
mid = mid + Math.imul(al8, bh7) | 0;
mid = mid + Math.imul(ah8, bl7) | 0;
hi = hi + Math.imul(ah8, bh7) | 0;
lo = lo + Math.imul(al7, bl8) | 0;
mid = mid + Math.imul(al7, bh8) | 0;
mid = mid + Math.imul(ah7, bl8) | 0;
hi = hi + Math.imul(ah7, bh8) | 0;
lo = lo + Math.imul(al6, bl9) | 0;
mid = mid + Math.imul(al6, bh9) | 0;
mid = mid + Math.imul(ah6, bl9) | 0;
hi = hi + Math.imul(ah6, bh9) | 0;
var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
w15 &= 0x3ffffff;
/* k = 16 */ lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = mid + Math.imul(ah9, bl7) | 0;
hi = Math.imul(ah9, bh7);
lo = lo + Math.imul(al8, bl8) | 0;
mid = mid + Math.imul(al8, bh8) | 0;
mid = mid + Math.imul(ah8, bl8) | 0;
hi = hi + Math.imul(ah8, bh8) | 0;
lo = lo + Math.imul(al7, bl9) | 0;
mid = mid + Math.imul(al7, bh9) | 0;
mid = mid + Math.imul(ah7, bl9) | 0;
hi = hi + Math.imul(ah7, bh9) | 0;
var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
w16 &= 0x3ffffff;
/* k = 17 */ lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = mid + Math.imul(ah9, bl8) | 0;
hi = Math.imul(ah9, bh8);
lo = lo + Math.imul(al8, bl9) | 0;
mid = mid + Math.imul(al8, bh9) | 0;
mid = mid + Math.imul(ah8, bl9) | 0;
hi = hi + Math.imul(ah8, bh9) | 0;
var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
w17 &= 0x3ffffff;
/* k = 18 */ lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = mid + Math.imul(ah9, bl9) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) comb10MulTo = smallMulTo;
function bigMulTo(self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for(var k = 0; k < out.length - 1; k++){
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for(var j = Math.max(0, k - self.length + 1); j <= maxJ; j++){
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = ncarry + (r / 0x4000000 | 0) | 0;
lo = lo + rword | 0;
rword = lo & 0x3ffffff;
ncarry = ncarry + (lo >>> 26) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) out.words[k] = carry;
else out.length--;
return out._strip();
}
function jumboMulTo(self, num, out) {
// Temporary disable, see https://github.com/indutny/bn.js/issues/211
// var fftm = new FFTM();
// return fftm.mulp(self, num, out);
return bigMulTo(self, num, out);
}
BN.prototype.mulTo = function mulTo(num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) res = comb10MulTo(this, num, out);
else if (len < 63) res = smallMulTo(this, num, out);
else if (len < 1024) res = bigMulTo(this, num, out);
else res = jumboMulTo(this, num, out);
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM(x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT(N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for(var i = 0; i < N; i++)t[i] = this.revBin(i, l, N);
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin(x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for(var i = 0; i < l; i++){
rb |= (x & 1) << l - i - 1;
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) {
for(var i = 0; i < N; i++){
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for(var s = 1; s < N; s <<= 1){
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for(var p = 0; p < N; p += l){
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for(var j = 0; j < s; j++){
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */ if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b(n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for(N = N / 2 | 0; N; N = N >>> 1)i++;
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate(rws, iws, N) {
if (N <= 1) return;
for(var i = 0; i < N / 2; i++){
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b(ws, N) {
var carry = 0;
for(var i = 0; i < N / 2; i++){
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) carry = 0;
else carry = w / 0x4000000 | 0;
}
return ws;
};
FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) {
var carry = 0;
for(var i = 0; i < len; i++){
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff;
carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff;
carry = carry >>> 13;
}
// Pad with zeroes
for(i = 2 * len; i < N; ++i)rws[i] = 0;
assert(carry === 0);
assert((carry & -8192) === 0);
};
FFTM.prototype.stub = function stub(N) {
var ph = new Array(N);
for(var i = 0; i < N; i++)ph[i] = 0;
return ph;
};
FFTM.prototype.mulp = function mulp(x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for(var i = 0; i < N; i++){
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out._strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul(num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(typeof num === "number");
assert(num < 0x4000000);
// Carry
var carry = 0;
for(var i = 0; i < this.length; i++){
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += w / 0x4000000 | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return isNegNum ? this.ineg() : this;
};
BN.prototype.muln = function muln(num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr() {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr() {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow(num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for(var i = 0; i < w.length; i++, res = res.sqr()){
if (w[i] !== 0) break;
}
if (++i < w.length) for(var q = res.sqr(); i < w.length; i++, q = q.sqr()){
if (w[i] === 0) continue;
res = res.mul(q);
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln(bits) {
assert(typeof bits === "number" && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = 0x3ffffff >>> 26 - r << 26 - r;
var i;
if (r !== 0) {
var carry = 0;
for(i = 0; i < this.length; i++){
var newCarry = this.words[i] & carryMask;
var c = (this.words[i] | 0) - newCarry << r;
this.words[i] = c | carry;
carry = newCarry >>> 26 - r;
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for(i = this.length - 1; i >= 0; i--)this.words[i + s] = this.words[i];
for(i = 0; i < s; i++)this.words[i] = 0;
this.length += s;
}
return this._strip();
};
BN.prototype.ishln = function ishln(bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn(bits, hint, extended) {
assert(typeof bits === "number" && bits >= 0);
var h;
if (hint) h = (hint - hint % 26) / 26;
else h = 0;
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for(var i = 0; i < s; i++)maskedWords.words[i] = this.words[i];
maskedWords.length = s;
}
if (s === 0) ;
else if (this.length > s) {
this.length -= s;
for(i = 0; i < this.length; i++)this.words[i] = this.words[i + s];
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for(i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--){
var word = this.words[i] | 0;
this.words[i] = carry << 26 - r | word >>> r;
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) maskedWords.words[maskedWords.length++] = carry;
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this._strip();
};
BN.prototype.ishrn = function ishrn(bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln(bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln(bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn(bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn(bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn(bit) {
assert(typeof bit === "number" && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn(bits) {
assert(typeof bits === "number" && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, "imaskn works only with positive numbers");
if (this.length <= s) return this;
if (r !== 0) s++;
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
this.words[this.length - 1] &= mask;
}
return this._strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn(bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn(num) {
assert(typeof num === "number");
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) <= num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn(num) {
this.words[0] += num;
// Carry
for(var i = 0; i < this.length && this.words[i] >= 0x4000000; i++){
this.words[i] -= 0x4000000;
if (i === this.length - 1) this.words[i + 1] = 1;
else this.words[i + 1]++;
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn(num) {
assert(typeof num === "number");
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else // Carry
for(var i = 0; i < this.length && this.words[i] < 0; i++){
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
return this._strip();
};
BN.prototype.addn = function addn(num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn(num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs() {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs() {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for(i = 0; i < num.length; i++){
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - (right / 0x4000000 | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for(; i < this.length - shift; i++){
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this._strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for(i = 0; i < this.length; i++){
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this._strip();
};
BN.prototype._wordDiv = function _wordDiv(num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== "mod") {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for(var i = 0; i < q.length; i++)q.words[i] = 0;
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) q.words[m] = 1;
}
for(var j = m - 1; j >= 0; j--){
var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min(qj / bhi | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while(a.negative !== 0){
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) a.negative ^= 1;
}
if (q) q.words[j] = qj;
}
if (q) q._strip();
a._strip();
// Denormalize
if (mode !== "div" && shift !== 0) a.iushrn(shift);
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod(num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) return {
div: new BN(0),
mod: new BN(0)
};
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== "mod") div = res.div.neg();
if (mode !== "div") {
mod = res.mod.neg();
if (positive && mod.negative !== 0) mod.iadd(num);
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== "mod") div = res.div.neg();
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== "div") {
mod = res.mod.neg();
if (positive && mod.negative !== 0) mod.isub(num);
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) return {
div: new BN(0),
mod: this
};
// Very short reduction
if (num.length === 1) {
if (mode === "div") return {
div: this.divn(num.words[0]),
mod: null
};
if (mode === "mod") return {
div: null,
mod: new BN(this.modrn(num.words[0]))
};
return {
div: this.divn(num.words[0]),
mod: new BN(this.modrn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div(num) {
return this.divmod(num, "div", false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod(num) {
return this.divmod(num, "mod", false).mod;
};
BN.prototype.umod = function umod(num) {
return this.divmod(num, "mod", true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound(num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modrn = function modrn(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var p = 67108864 % num;
var acc = 0;
for(var i = this.length - 1; i >= 0; i--)acc = (p * acc + (this.words[i] | 0)) % num;
return isNegNum ? -acc : acc;
};
// WARNING: DEPRECATED
BN.prototype.modn = function modn(num) {
return this.modrn(num);
};
// In-place division by number
BN.prototype.idivn = function idivn(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var carry = 0;
for(var i = this.length - 1; i >= 0; i--){
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = w / num | 0;
carry = w % num;
}
this._strip();
return isNegNum ? this.ineg() : this;
};
BN.prototype.divn = function divn(num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd(p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) x = x.umod(p);
else x = x.clone();
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while(x.isEven() && y.isEven()){
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while(!x.isZero()){
for(var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while(i-- > 0){
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for(var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while(j-- > 0){
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp(p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) a = a.umod(p);
else a = a.clone();
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while(a.cmpn(1) > 0 && b.cmpn(1) > 0){
for(var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while(i-- > 0){
if (x1.isOdd()) x1.iadd(delta);
x1.iushrn(1);
}
}
for(var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while(j-- > 0){
if (x2.isOdd()) x2.iadd(delta);
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) res = x1;
else res = x2;
if (res.cmpn(0) < 0) res.iadd(p);
return res;
};
BN.prototype.gcd = function gcd(num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for(var shift = 0; a.isEven() && b.isEven(); shift++){
a.iushrn(1);
b.iushrn(1);
}
do {
while(a.isEven())a.iushrn(1);
while(b.isEven())b.iushrn(1);
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) break;
a.isub(b);
}while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm(num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven() {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd() {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln(num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn(bit) {
assert(typeof bit === "number");
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for(var i = s; carry !== 0 && i < this.length; i++){
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero() {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn(num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this._strip();
var res;
if (this.length > 1) res = 1;
else {
if (negative) num = -num;
assert(num <= 0x3ffffff, "Number is too big");
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp(num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp(num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for(var i = this.length - 1; i >= 0; i--){
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) res = -1;
else if (a > b) res = 1;
break;
}
return res;
};
BN.prototype.gtn = function gtn(num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt(num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten(num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte(num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn(num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt(num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten(num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte(num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn(num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq(num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red(num) {
return new Red(num);
};
BN.prototype.toRed = function toRed(ctx) {
assert(!this.red, "Already a number in reduction context");
assert(this.negative === 0, "red works only with positives");
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed() {
assert(this.red, "fromRed works only with numbers in reduction context");
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed(ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed(ctx) {
assert(!this.red, "Already a number in reduction context");
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd(num) {
assert(this.red, "redAdd works only with red numbers");
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd(num) {
assert(this.red, "redIAdd works only with red numbers");
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub(num) {
assert(this.red, "redSub works only with red numbers");
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub(num) {
assert(this.red, "redISub works only with red numbers");
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl(num) {
assert(this.red, "redShl works only with red numbers");
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul(num) {
assert(this.red, "redMul works only with red numbers");
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul(num) {
assert(this.red, "redMul works only with red numbers");
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr() {
assert(this.red, "redSqr works only with red numbers");
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr() {
assert(this.red, "redISqr works only with red numbers");
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt() {
assert(this.red, "redSqrt works only with red numbers");
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm() {
assert(this.red, "redInvm works only with red numbers");
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg() {
assert(this.red, "redNeg works only with red numbers");
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow(num) {
assert(this.red && !num.red, "redPow(normalNum)");
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime(name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp() {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce(num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
}while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) r.isub(this.p);
else if (r.strip !== undefined) // r is a BN v4 instance
r.strip();
else // r is a BN v5 instance
r._strip();
return r;
};
MPrime.prototype.split = function split(input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK(num) {
return num.imul(this.k);
};
function K256() {
MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
}
inherits(K256, MPrime);
K256.prototype.split = function split(input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for(var i = 0; i < outLen; i++)output.words[i] = input.words[i];
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for(i = 10; i < input.length; i++){
var next = input.words[i] | 0;
input.words[i - 10] = (next & mask) << 4 | prev >>> 22;
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) input.length -= 10;
else input.length -= 9;
};
K256.prototype.imulK = function imulK(num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for(var i = 0; i < num.length; i++){
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + (lo / 0x4000000 | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) num.length--;
}
return num;
};
function P224() {
MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
}
inherits(P224, MPrime);
function P192() {
MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
}
inherits(P192, MPrime);
function P25519() {
// 2 ^ 255 - 19
MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK(num) {
// K = 0x13
var carry = 0;
for(var i = 0; i < num.length; i++){
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) num.words[num.length++] = carry;
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime(name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === "k256") prime = new K256();
else if (name === "p224") prime = new P224();
else if (name === "p192") prime = new P192();
else if (name === "p25519") prime = new P25519();
else throw new Error("Unknown prime " + name);
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red(m) {
if (typeof m === "string") {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), "modulus must be greater than 1");
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1(a) {
assert(a.negative === 0, "red works only with positives");
assert(a.red, "red works only with red numbers");
};
Red.prototype._verify2 = function _verify2(a, b) {
assert((a.negative | b.negative) === 0, "red works only with positives");
assert(a.red && a.red === b.red, "red works only with red numbers");
};
Red.prototype.imod = function imod(a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
move(a, a.umod(this.m)._forceRed(this));
return a;
};
Red.prototype.neg = function neg(a) {
if (a.isZero()) return a.clone();
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add(a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) res.isub(this.m);
return res._forceRed(this);
};
Red.prototype.iadd = function iadd(a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) res.isub(this.m);
return res;
};
Red.prototype.sub = function sub(a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) res.iadd(this.m);
return res._forceRed(this);
};
Red.prototype.isub = function isub(a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) res.iadd(this.m);
return res;
};
Red.prototype.shl = function shl(a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul(a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul(a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr(a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr(a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt(a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while(!q.isZero() && q.andln(1) === 0){
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while(this.pow(z, lpow).cmp(nOne) !== 0)z.redIAdd(nOne);
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while(t.cmp(one) !== 0){
var tmp = t;
for(var i = 0; tmp.cmp(one) !== 0; i++)tmp = tmp.redSqr();
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm(a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else return this.imod(inv);
};
Red.prototype.pow = function pow(a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for(var i = 2; i < wnd.length; i++)wnd[i] = this.mul(wnd[i - 1], a);
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) start = 26;
for(i = num.length - 1; i >= 0; i--){
var word = num.words[i];
for(var j = start - 1; j >= 0; j--){
var bit = word >> j & 1;
if (res !== wnd[0]) res = this.sqr(res);
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo(num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom(num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont(num) {
return new Mont(num);
};
function Mont(m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) this.shift += 26 - this.shift % 26;
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo(num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom(num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul(a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) res = u.isub(this.m);
else if (u.cmpn(0) < 0) res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.mul = function mul(a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) res = u.isub(this.m);
else if (u.cmpn(0) < 0) res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.invm = function invm(a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(module, this);
},{"buffer":"jhUEF"}],"4ji3p":[function(require,module,exports) {
var basex = require("base-x");
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
module.exports = basex(ALPHABET);
},{"base-x":"inVbl"}],"inVbl":[function(require,module,exports) {
"use strict";
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
// @ts-ignore
var _Buffer = require("safe-buffer").Buffer;
function base(ALPHABET) {
if (ALPHABET.length >= 255) throw new TypeError("Alphabet too long");
var BASE_MAP = new Uint8Array(256);
for(var j = 0; j < BASE_MAP.length; j++)BASE_MAP[j] = 255;
for(var i = 0; i < ALPHABET.length; i++){
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) throw new TypeError(x + " is ambiguous");
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
;
var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
;
function encode(source) {
if (Array.isArray(source) || source instanceof Uint8Array) source = _Buffer.from(source);
if (!_Buffer.isBuffer(source)) throw new TypeError("Expected Buffer");
if (source.length === 0) return "";
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while(pbegin !== pend && source[pbegin] === 0){
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while(pbegin !== pend){
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for(var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++){
carry += 256 * b58[it1] >>> 0;
b58[it1] = carry % BASE >>> 0;
carry = carry / BASE >>> 0;
}
if (carry !== 0) throw new Error("Non-zero carry");
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while(it2 !== size && b58[it2] === 0)it2++;
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for(; it2 < size; ++it2)str += ALPHABET.charAt(b58[it2]);
return str;
}
function decodeUnsafe(source) {
if (typeof source !== "string") throw new TypeError("Expected String");
if (source.length === 0) return _Buffer.alloc(0);
var psz = 0;
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while(source[psz] === LEADER){
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (source.length - psz) * FACTOR + 1 >>> 0 // log(58) / log(256), rounded up.
;
var b256 = new Uint8Array(size);
// Process the characters.
while(source[psz]){
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) return;
var i = 0;
for(var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++){
carry += BASE * b256[it3] >>> 0;
b256[it3] = carry % 256 >>> 0;
carry = carry / 256 >>> 0;
}
if (carry !== 0) throw new Error("Non-zero carry");
length = i;
psz++;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while(it4 !== size && b256[it4] === 0)it4++;
var vch = _Buffer.allocUnsafe(zeroes + (size - it4));
vch.fill(0x00, 0, zeroes);
var j = zeroes;
while(it4 !== size)vch[j++] = b256[it4++];
return vch;
}
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) return buffer;
throw new Error("Non-base" + BASE + " character");
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
module.exports = base;
},{"safe-buffer":"eW7r9"}],"eW7r9":[function(require,module,exports) {
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ /* eslint-disable node/no-deprecated-api */ var buffer = require("buffer");
var Buffer = buffer.Buffer;
// alternative to using Object.keys for old browsers
function copyProps(src, dst) {
for(var key in src)dst[key] = src[key];
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) module.exports = buffer;
else {
// Copy properties from require('buffer')
copyProps(buffer, exports);
exports.Buffer = SafeBuffer;
}
function SafeBuffer(arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length);
}
SafeBuffer.prototype = Object.create(Buffer.prototype);
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer);
SafeBuffer.from = function(arg, encodingOrOffset, length) {
if (typeof arg === "number") throw new TypeError("Argument must not be a number");
return Buffer(arg, encodingOrOffset, length);
};
SafeBuffer.alloc = function(size, fill, encoding) {
if (typeof size !== "number") throw new TypeError("Argument must be a number");
var buf = Buffer(size);
if (fill !== undefined) {
if (typeof encoding === "string") buf.fill(fill, encoding);
else buf.fill(fill);
} else buf.fill(0);
return buf;
};
SafeBuffer.allocUnsafe = function(size) {
if (typeof size !== "number") throw new TypeError("Argument must be a number");
return Buffer(size);
};
SafeBuffer.allocUnsafeSlow = function(size) {
if (typeof size !== "number") throw new TypeError("Argument must be a number");
return buffer.SlowBuffer(size);
};
},{"buffer":"dvCeB"}],"feCA6":[function(require,module,exports) {
"use strict";
// This is free and unencumbered software released into the public domain.
// See LICENSE.md for more information.
//
// Utilities
//
/**
* @param {number} a The number to test.
* @param {number} min The minimum value in the range, inclusive.
* @param {number} max The maximum value in the range, inclusive.
* @return {boolean} True if a >= min and a <= max.
*/ function inRange(a, min, max) {
return min <= a && a <= max;
}
/**
* @param {*} o
* @return {Object}
*/ function ToDictionary(o) {
if (o === undefined) return {};
if (o === Object(o)) return o;
throw TypeError("Could not convert argument to dictionary");
}
/**
* @param {string} string Input string of UTF-16 code units.
* @return {!Array.<number>} Code points.
*/ function stringToCodePoints(string) {
// https://heycam.github.io/webidl/#dfn-obtain-unicode
// 1. Let S be the DOMString value.
var s = String(string);
// 2. Let n be the length of S.
var n = s.length;
// 3. Initialize i to 0.
var i = 0;
// 4. Initialize U to be an empty sequence of Unicode characters.
var u = [];
// 5. While i < n:
while(i < n){
// 1. Let c be the code unit in S at index i.
var c = s.charCodeAt(i);
// 2. Depending on the value of c:
// c < 0xD800 or c > 0xDFFF
if (c < 0xD800 || c > 0xDFFF) // Append to U the Unicode character with code point c.
u.push(c);
else if (0xDC00 <= c && c <= 0xDFFF) // Append to U a U+FFFD REPLACEMENT CHARACTER.
u.push(0xFFFD);
else if (0xD800 <= c && c <= 0xDBFF) {
// 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
// CHARACTER.
if (i === n - 1) u.push(0xFFFD);
else {
// 1. Let d be the code unit in S at index i+1.
var d = string.charCodeAt(i + 1);
// 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
if (0xDC00 <= d && d <= 0xDFFF) {
// 1. Let a be c & 0x3FF.
var a = c & 0x3FF;
// 2. Let b be d & 0x3FF.
var b = d & 0x3FF;
// 3. Append to U the Unicode character with code point
// 2^16+2^10*a+b.
u.push(0x10000 + (a << 10) + b);
// 4. Set i to i+1.
i += 1;
} else u.push(0xFFFD);
}
}
// 3. Set i to i+1.
i += 1;
}
// 6. Return U.
return u;
}
/**
* @param {!Array.<number>} code_points Array of code points.
* @return {string} string String of UTF-16 code units.
*/ function codePointsToString(code_points) {
var s = "";
for(var i = 0; i < code_points.length; ++i){
var cp = code_points[i];
if (cp <= 0xFFFF) s += String.fromCharCode(cp);
else {
cp -= 0x10000;
s += String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00);
}
}
return s;
}
//
// Implementation of Encoding specification
// https://encoding.spec.whatwg.org/
//
//
// 3. Terminology
//
/**
* End-of-stream is a special token that signifies no more tokens
* are in the stream.
* @const
*/ var end_of_stream = -1;
/**
* A stream represents an ordered sequence of tokens.
*
* @constructor
* @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
* stream.
*/ function Stream(tokens) {
/** @type {!Array.<number>} */ this.tokens = [].slice.call(tokens);
}
Stream.prototype = {
/**
* @return {boolean} True if end-of-stream has been hit.
*/ endOfStream: function() {
return !this.tokens.length;
},
/**
* When a token is read from a stream, the first token in the
* stream must be returned and subsequently removed, and
* end-of-stream must be returned otherwise.
*
* @return {number} Get the next token from the stream, or
* end_of_stream.
*/ read: function() {
if (!this.tokens.length) return end_of_stream;
return this.tokens.shift();
},
/**
* When one or more tokens are prepended to a stream, those tokens
* must be inserted, in given order, before the first token in the
* stream.
*
* @param {(number|!Array.<number>)} token The token(s) to prepend to the stream.
*/ prepend: function(token) {
if (Array.isArray(token)) {
var tokens = token;
while(tokens.length)this.tokens.unshift(tokens.pop());
} else this.tokens.unshift(token);
},
/**
* When one or more tokens are pushed to a stream, those tokens
* must be inserted, in given order, after the last token in the
* stream.
*
* @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
*/ push: function(token) {
if (Array.isArray(token)) {
var tokens = token;
while(tokens.length)this.tokens.push(tokens.shift());
} else this.tokens.push(token);
}
};
//
// 4. Encodings
//
// 4.1 Encoders and decoders
/** @const */ var finished = -1;
/**
* @param {boolean} fatal If true, decoding errors raise an exception.
* @param {number=} opt_code_point Override the standard fallback code point.
* @return {number} The code point to insert on a decoding error.
*/ function decoderError(fatal, opt_code_point) {
if (fatal) throw TypeError("Decoder error");
return opt_code_point || 0xFFFD;
}
//
// 7. API
//
/** @const */ var DEFAULT_ENCODING = "utf-8";
// 7.1 Interface TextDecoder
/**
* @constructor
* @param {string=} encoding The label of the encoding;
* defaults to 'utf-8'.
* @param {Object=} options
*/ function TextDecoder(encoding, options) {
if (!(this instanceof TextDecoder)) return new TextDecoder(encoding, options);
encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
if (encoding !== DEFAULT_ENCODING) throw new Error("Encoding not supported. Only utf-8 is supported");
options = ToDictionary(options);
/** @private @type {boolean} */ this._streaming = false;
/** @private @type {boolean} */ this._BOMseen = false;
/** @private @type {?Decoder} */ this._decoder = null;
/** @private @type {boolean} */ this._fatal = Boolean(options["fatal"]);
/** @private @type {boolean} */ this._ignoreBOM = Boolean(options["ignoreBOM"]);
Object.defineProperty(this, "encoding", {
value: "utf-8"
});
Object.defineProperty(this, "fatal", {
value: this._fatal
});
Object.defineProperty(this, "ignoreBOM", {
value: this._ignoreBOM
});
}
TextDecoder.prototype = {
/**
* @param {ArrayBufferView=} input The buffer of bytes to decode.
* @param {Object=} options
* @return {string} The decoded string.
*/ decode: function decode(input, options) {
var bytes;
if (typeof input === "object" && input instanceof ArrayBuffer) bytes = new Uint8Array(input);
else if (typeof input === "object" && "buffer" in input && input.buffer instanceof ArrayBuffer) bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
else bytes = new Uint8Array(0);
options = ToDictionary(options);
if (!this._streaming) {
this._decoder = new UTF8Decoder({
fatal: this._fatal
});
this._BOMseen = false;
}
this._streaming = Boolean(options["stream"]);
var input_stream = new Stream(bytes);
var code_points = [];
/** @type {?(number|!Array.<number>)} */ var result;
while(!input_stream.endOfStream()){
result = this._decoder.handler(input_stream, input_stream.read());
if (result === finished) break;
if (result === null) continue;
if (Array.isArray(result)) code_points.push.apply(code_points, result);
else code_points.push(result);
}
if (!this._streaming) {
do {
result = this._decoder.handler(input_stream, input_stream.read());
if (result === finished) break;
if (result === null) continue;
if (Array.isArray(result)) code_points.push.apply(code_points, result);
else code_points.push(result);
}while (!input_stream.endOfStream());
this._decoder = null;
}
if (code_points.length) // If encoding is one of utf-8, utf-16be, and utf-16le, and
// ignore BOM flag and BOM seen flag are unset, run these
// subsubsteps:
{
if ([
"utf-8"
].indexOf(this.encoding) !== -1 && !this._ignoreBOM && !this._BOMseen) {
// If token is U+FEFF, set BOM seen flag.
if (code_points[0] === 0xFEFF) {
this._BOMseen = true;
code_points.shift();
} else // Otherwise, if token is not end-of-stream, set BOM seen
// flag and append token to output.
this._BOMseen = true;
}
}
return codePointsToString(code_points);
}
};
// 7.2 Interface TextEncoder
/**
* @constructor
* @param {string=} encoding The label of the encoding;
* defaults to 'utf-8'.
* @param {Object=} options
*/ function TextEncoder(encoding, options) {
if (!(this instanceof TextEncoder)) return new TextEncoder(encoding, options);
encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
if (encoding !== DEFAULT_ENCODING) throw new Error("Encoding not supported. Only utf-8 is supported");
options = ToDictionary(options);
/** @private @type {boolean} */ this._streaming = false;
/** @private @type {?Encoder} */ this._encoder = null;
/** @private @type {{fatal: boolean}} */ this._options = {
fatal: Boolean(options["fatal"])
};
Object.defineProperty(this, "encoding", {
value: "utf-8"
});
}
TextEncoder.prototype = {
/**
* @param {string=} opt_string The string to encode.
* @param {Object=} options
* @return {Uint8Array} Encoded bytes, as a Uint8Array.
*/ encode: function encode(opt_string, options) {
opt_string = opt_string ? String(opt_string) : "";
options = ToDictionary(options);
// NOTE: This option is nonstandard. None of the encodings
// permitted for encoding (i.e. UTF-8, UTF-16) are stateful,
// so streaming is not necessary.
if (!this._streaming) this._encoder = new UTF8Encoder(this._options);
this._streaming = Boolean(options["stream"]);
var bytes = [];
var input_stream = new Stream(stringToCodePoints(opt_string));
/** @type {?(number|!Array.<number>)} */ var result;
while(!input_stream.endOfStream()){
result = this._encoder.handler(input_stream, input_stream.read());
if (result === finished) break;
if (Array.isArray(result)) bytes.push.apply(bytes, result);
else bytes.push(result);
}
if (!this._streaming) {
while(true){
result = this._encoder.handler(input_stream, input_stream.read());
if (result === finished) break;
if (Array.isArray(result)) bytes.push.apply(bytes, result);
else bytes.push(result);
}
this._encoder = null;
}
return new Uint8Array(bytes);
}
};
//
// 8. The encoding
//
// 8.1 utf-8
/**
* @constructor
* @implements {Decoder}
* @param {{fatal: boolean}} options
*/ function UTF8Decoder(options) {
var fatal = options.fatal;
// utf-8's decoder's has an associated utf-8 code point, utf-8
// bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
// lower boundary (initially 0x80), and a utf-8 upper boundary
// (initially 0xBF).
var /** @type {number} */ utf8_code_point = 0, /** @type {number} */ utf8_bytes_seen = 0, /** @type {number} */ utf8_bytes_needed = 0, /** @type {number} */ utf8_lower_boundary = 0x80, /** @type {number} */ utf8_upper_boundary = 0xBF;
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return {?(number|!Array.<number>)} The next code point(s)
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/ this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
utf8_bytes_needed = 0;
return decoderError(fatal);
}
// 2. If byte is end-of-stream, return finished.
if (bite === end_of_stream) return finished;
// 3. If utf-8 bytes needed is 0, based on byte:
if (utf8_bytes_needed === 0) {
// 0x00 to 0x7F
if (inRange(bite, 0x00, 0x7F)) // Return a code point whose value is byte.
return bite;
// 0xC2 to 0xDF
if (inRange(bite, 0xC2, 0xDF)) {
// Set utf-8 bytes needed to 1 and utf-8 code point to byte
// − 0xC0.
utf8_bytes_needed = 1;
utf8_code_point = bite - 0xC0;
} else if (inRange(bite, 0xE0, 0xEF)) {
// 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
if (bite === 0xE0) utf8_lower_boundary = 0xA0;
// 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
if (bite === 0xED) utf8_upper_boundary = 0x9F;
// 3. Set utf-8 bytes needed to 2 and utf-8 code point to
// byte − 0xE0.
utf8_bytes_needed = 2;
utf8_code_point = bite - 0xE0;
} else if (inRange(bite, 0xF0, 0xF4)) {
// 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
if (bite === 0xF0) utf8_lower_boundary = 0x90;
// 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
if (bite === 0xF4) utf8_upper_boundary = 0x8F;
// 3. Set utf-8 bytes needed to 3 and utf-8 code point to
// byte − 0xF0.
utf8_bytes_needed = 3;
utf8_code_point = bite - 0xF0;
} else // Return error.
return decoderError(fatal);
// Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
// point to utf-8 code point << (6 × utf-8 bytes needed) and
// return continue.
utf8_code_point = utf8_code_point << 6 * utf8_bytes_needed;
return null;
}
// 4. If byte is not in the range utf-8 lower boundary to utf-8
// upper boundary, run these substeps:
if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
// 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
// bytes seen to 0, set utf-8 lower boundary to 0x80, and set
// utf-8 upper boundary to 0xBF.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 2. Prepend byte to stream.
stream.prepend(bite);
// 3. Return error.
return decoderError(fatal);
}
// 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
// to 0xBF.
utf8_lower_boundary = 0x80;
utf8_upper_boundary = 0xBF;
// 6. Increase utf-8 bytes seen by one and set utf-8 code point
// to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
// needed − utf-8 bytes seen)).
utf8_bytes_seen += 1;
utf8_code_point += bite - 0x80 << 6 * (utf8_bytes_needed - utf8_bytes_seen);
// 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
// continue.
if (utf8_bytes_seen !== utf8_bytes_needed) return null;
// 8. Let code point be utf-8 code point.
var code_point = utf8_code_point;
// 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
// seen to 0.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
// 10. Return a code point whose value is code point.
return code_point;
};
}
/**
* @constructor
* @implements {Encoder}
* @param {{fatal: boolean}} options
*/ function UTF8Encoder(options) {
var fatal = options.fatal;
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/ this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) return finished;
// 2. If code point is in the range U+0000 to U+007F, return a
// byte whose value is code point.
if (inRange(code_point, 0x0000, 0x007f)) return code_point;
// 3. Set count and offset based on the range code point is in:
var count, offset;
// U+0080 to U+07FF: 1 and 0xC0
if (inRange(code_point, 0x0080, 0x07FF)) {
count = 1;
offset = 0xC0;
} else if (inRange(code_point, 0x0800, 0xFFFF)) {
count = 2;
offset = 0xE0;
} else if (inRange(code_point, 0x10000, 0x10FFFF)) {
count = 3;
offset = 0xF0;
}
// 4.Let bytes be a byte sequence whose first byte is (code
// point >> (6 × count)) + offset.
var bytes = [
(code_point >> 6 * count) + offset
];
// 5. Run these substeps while count is greater than 0:
while(count > 0){
// 1. Set temp to code point >> (6 × (count − 1)).
var temp = code_point >> 6 * (count - 1);
// 2. Append to bytes 0x80 | (temp & 0x3F).
bytes.push(0x80 | temp & 0x3F);
// 3. Decrease count by one.
count -= 1;
}
// 6. Return bytes bytes, in order.
return bytes;
};
}
exports.TextEncoder = TextEncoder;
exports.TextDecoder = TextDecoder;
},{}],"kjmPo":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Assignable = exports.Enum = void 0;
/** @hidden @module */ class Enum {
constructor(properties){
if (Object.keys(properties).length !== 1) throw new Error("Enum can only take single value");
Object.keys(properties).map((key)=>{
this[key] = properties[key];
this.enum = key;
});
}
}
exports.Enum = Enum;
class Assignable {
constructor(properties){
Object.keys(properties).map((key)=>{
this[key] = properties[key];
});
}
}
exports.Assignable = Assignable;
},{}],"l5Tuv":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BrowserLocalStorageKeyStore = void 0;
const keystore_1 = require("./keystore");
const key_pair_1 = require("../utils/key_pair");
const LOCAL_STORAGE_KEY_PREFIX = "near-api-js:keystore:";
/**
* This class is used to store keys in the browsers local storage.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#key-store}
* @example
* ```js
* import { connect, keyStores } from 'near-api-js';
*
* const keyStore = new keyStores.BrowserLocalStorageKeyStore();
* const config = {
* keyStore, // instance of BrowserLocalStorageKeyStore
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org',
* walletUrl: 'https://wallet.testnet.near.org',
* helperUrl: 'https://helper.testnet.near.org',
* explorerUrl: 'https://explorer.testnet.near.org'
* };
*
* // inside an async function
* const near = await connect(config)
* ```
*/ class BrowserLocalStorageKeyStore extends keystore_1.KeyStore {
/**
* @param localStorage defaults to window.localStorage
* @param prefix defaults to `near-api-js:keystore:`
*/ constructor(localStorage = window.localStorage, prefix = LOCAL_STORAGE_KEY_PREFIX){
super();
this.localStorage = localStorage;
this.prefix = prefix;
}
/**
* Stores a {@link KeyPair} in local storage.
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/ async setKey(networkId, accountId, keyPair) {
this.localStorage.setItem(this.storageKeyForSecretKey(networkId, accountId), keyPair.toString());
}
/**
* Gets a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/ async getKey(networkId, accountId) {
const value = this.localStorage.getItem(this.storageKeyForSecretKey(networkId, accountId));
if (!value) return null;
return key_pair_1.KeyPair.fromString(value);
}
/**
* Removes a {@link KeyPair} from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/ async removeKey(networkId, accountId) {
this.localStorage.removeItem(this.storageKeyForSecretKey(networkId, accountId));
}
/**
* Removes all items that start with `prefix` from local storage
*/ async clear() {
for (const key of this.storageKeys())if (key.startsWith(this.prefix)) this.localStorage.removeItem(key);
}
/**
* Get the network(s) from local storage
* @returns {Promise<string[]>}
*/ async getNetworks() {
const result = new Set();
for (const key of this.storageKeys())if (key.startsWith(this.prefix)) {
const parts = key.substring(this.prefix.length).split(":");
result.add(parts[1]);
}
return Array.from(result.values());
}
/**
* Gets the account(s) from local storage
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns{Promise<string[]>}
*/ async getAccounts(networkId) {
const result = new Array();
for (const key of this.storageKeys())if (key.startsWith(this.prefix)) {
const parts = key.substring(this.prefix.length).split(":");
if (parts[1] === networkId) result.push(parts[0]);
}
return result;
}
/**
* @hidden
* Helper function to retrieve a local storage key
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the storage keythat's sought
* @returns {string} An example might be: `near-api-js:keystore:near-friend:default`
*/ storageKeyForSecretKey(networkId, accountId) {
return `${this.prefix}${accountId}:${networkId}`;
}
/** @hidden */ *storageKeys() {
for(let i = 0; i < this.localStorage.length; i++)yield this.localStorage.key(i);
}
}
exports.BrowserLocalStorageKeyStore = BrowserLocalStorageKeyStore;
},{"./keystore":"5Moei","../utils/key_pair":"kBQFP"}],"kgqhu":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MergeKeyStore = void 0;
const keystore_1 = require("./keystore");
class MergeKeyStore extends keystore_1.KeyStore {
/**
* @param keyStores read calls are attempted from start to end of array
* @param options.writeKeyStoreIndex the keystore index that will receive all write calls
*/ constructor(keyStores, options = {
writeKeyStoreIndex: 0
}){
super();
this.options = options;
this.keyStores = keyStores;
}
/**
* Store a {@link KeyPain} to the first index of a key store array
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @param keyPair The key pair to store in local storage
*/ async setKey(networkId, accountId, keyPair) {
await this.keyStores[this.options.writeKeyStoreIndex].setKey(networkId, accountId, keyPair);
}
/**
* Gets a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
* @returns {Promise<KeyPair>}
*/ async getKey(networkId, accountId) {
for (const keyStore of this.keyStores){
const keyPair = await keyStore.getKey(networkId, accountId);
if (keyPair) return keyPair;
}
return null;
}
/**
* Removes a {@link KeyPair} from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account tied to the key pair
*/ async removeKey(networkId, accountId) {
for (const keyStore of this.keyStores)await keyStore.removeKey(networkId, accountId);
}
/**
* Removes all items from each key store
*/ async clear() {
for (const keyStore of this.keyStores)await keyStore.clear();
}
/**
* Get the network(s) from the array of key stores
* @returns {Promise<string[]>}
*/ async getNetworks() {
const result = new Set();
for (const keyStore of this.keyStores)for (const network of (await keyStore.getNetworks()))result.add(network);
return Array.from(result);
}
/**
* Gets the account(s) from the array of key stores
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns{Promise<string[]>}
*/ async getAccounts(networkId) {
const result = new Set();
for (const keyStore of this.keyStores)for (const account of (await keyStore.getAccounts(networkId)))result.add(account);
return Array.from(result);
}
/** @hidden */ toString() {
return `MergeKeyStore(${this.keyStores.join(", ")})`;
}
}
exports.MergeKeyStore = MergeKeyStore;
},{"./keystore":"5Moei"}],"gtZXS":[function(require,module,exports) {
"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: function() {
return m[k];
}
});
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WalletConnection = exports.WalletAccount = exports.ConnectedWalletAccount = exports.Near = exports.KeyPair = exports.Signer = exports.InMemorySigner = exports.Contract = exports.Connection = exports.Account = exports.multisig = exports.validators = exports.transactions = exports.utils = exports.providers = exports.accountCreator = void 0;
/** @hidden @module */ const providers = __importStar(require("./providers"));
exports.providers = providers;
const utils = __importStar(require("./utils"));
exports.utils = utils;
const transactions = __importStar(require("./transaction"));
exports.transactions = transactions;
const validators = __importStar(require("./validators"));
exports.validators = validators;
const account_1 = require("./account");
Object.defineProperty(exports, "Account", {
enumerable: true,
get: function() {
return account_1.Account;
}
});
const multisig = __importStar(require("./account_multisig"));
exports.multisig = multisig;
const accountCreator = __importStar(require("./account_creator"));
exports.accountCreator = accountCreator;
const connection_1 = require("./connection");
Object.defineProperty(exports, "Connection", {
enumerable: true,
get: function() {
return connection_1.Connection;
}
});
const signer_1 = require("./signer");
Object.defineProperty(exports, "Signer", {
enumerable: true,
get: function() {
return signer_1.Signer;
}
});
Object.defineProperty(exports, "InMemorySigner", {
enumerable: true,
get: function() {
return signer_1.InMemorySigner;
}
});
const contract_1 = require("./contract");
Object.defineProperty(exports, "Contract", {
enumerable: true,
get: function() {
return contract_1.Contract;
}
});
const key_pair_1 = require("./utils/key_pair");
Object.defineProperty(exports, "KeyPair", {
enumerable: true,
get: function() {
return key_pair_1.KeyPair;
}
});
const near_1 = require("./near");
Object.defineProperty(exports, "Near", {
enumerable: true,
get: function() {
return near_1.Near;
}
});
// TODO: Deprecate and remove WalletAccount
const wallet_account_1 = require("./wallet-account");
Object.defineProperty(exports, "ConnectedWalletAccount", {
enumerable: true,
get: function() {
return wallet_account_1.ConnectedWalletAccount;
}
});
Object.defineProperty(exports, "WalletAccount", {
enumerable: true,
get: function() {
return wallet_account_1.WalletAccount;
}
});
Object.defineProperty(exports, "WalletConnection", {
enumerable: true,
get: function() {
return wallet_account_1.WalletConnection;
}
});
},{"./providers":"gtL2a","./utils":"jOCMH","./transaction":"jJQ5a","./validators":"6CFD9","./account":"hxSQV","./account_multisig":"7q1du","./account_creator":"aQbxV","./connection":"3ThJM","./signer":"a6bzI","./contract":"guo0T","./utils/key_pair":"kBQFP","./near":"9Ying","./wallet-account":"dHM3Z"}],"gtL2a":[function(require,module,exports) {
"use strict";
/** @hidden @module */ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ErrorContext = exports.TypedError = exports.getTransactionLastResult = exports.FinalExecutionStatusBasic = exports.JsonRpcProvider = exports.Provider = void 0;
const provider_1 = require("./provider");
Object.defineProperty(exports, "Provider", {
enumerable: true,
get: function() {
return provider_1.Provider;
}
});
Object.defineProperty(exports, "getTransactionLastResult", {
enumerable: true,
get: function() {
return provider_1.getTransactionLastResult;
}
});
Object.defineProperty(exports, "FinalExecutionStatusBasic", {
enumerable: true,
get: function() {
return provider_1.FinalExecutionStatusBasic;
}
});
const json_rpc_provider_1 = require("./json-rpc-provider");
Object.defineProperty(exports, "JsonRpcProvider", {
enumerable: true,
get: function() {
return json_rpc_provider_1.JsonRpcProvider;
}
});
Object.defineProperty(exports, "TypedError", {
enumerable: true,
get: function() {
return json_rpc_provider_1.TypedError;
}
});
Object.defineProperty(exports, "ErrorContext", {
enumerable: true,
get: function() {
return json_rpc_provider_1.ErrorContext;
}
});
},{"./provider":"cUEh0","./json-rpc-provider":"kzXVU"}],"cUEh0":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
/**
* NEAR RPC API request types and responses
* @module
*/ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTransactionLastResult = exports.Provider = exports.IdType = exports.FinalExecutionStatusBasic = exports.ExecutionStatusBasic = void 0;
var ExecutionStatusBasic;
(function(ExecutionStatusBasic) {
ExecutionStatusBasic["Unknown"] = "Unknown";
ExecutionStatusBasic["Pending"] = "Pending";
ExecutionStatusBasic["Failure"] = "Failure";
})(ExecutionStatusBasic = exports.ExecutionStatusBasic || (exports.ExecutionStatusBasic = {}));
var FinalExecutionStatusBasic;
(function(FinalExecutionStatusBasic) {
FinalExecutionStatusBasic["NotStarted"] = "NotStarted";
FinalExecutionStatusBasic["Started"] = "Started";
FinalExecutionStatusBasic["Failure"] = "Failure";
})(FinalExecutionStatusBasic = exports.FinalExecutionStatusBasic || (exports.FinalExecutionStatusBasic = {}));
var IdType;
(function(IdType) {
IdType["Transaction"] = "transaction";
IdType["Receipt"] = "receipt";
})(IdType = exports.IdType || (exports.IdType = {}));
/** @hidden */ class Provider {
}
exports.Provider = Provider;
/** @hidden */ function getTransactionLastResult(txResult) {
if (typeof txResult.status === "object" && typeof txResult.status.SuccessValue === "string") {
const value = Buffer.from(txResult.status.SuccessValue, "base64").toString();
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
return null;
}
exports.getTransactionLastResult = getTransactionLastResult;
},{"buffer":"dvCeB"}],"kzXVU":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.JsonRpcProvider = exports.ErrorContext = exports.TypedError = void 0;
/**
* This module contains the {@link JsonRpcProvider} client class
* which can be used to interact with the NEAR RPC API.
* @see {@link providers/provider} for a list of request and response types
*/ const depd_1 = __importDefault(require("depd"));
const provider_1 = require("./provider");
const web_1 = require("../utils/web");
const errors_1 = require("../utils/errors");
Object.defineProperty(exports, "TypedError", {
enumerable: true,
get: function() {
return errors_1.TypedError;
}
});
Object.defineProperty(exports, "ErrorContext", {
enumerable: true,
get: function() {
return errors_1.ErrorContext;
}
});
const borsh_1 = require("borsh");
const exponential_backoff_1 = __importDefault(require("../utils/exponential-backoff"));
const rpc_errors_1 = require("../utils/rpc_errors");
// Default number of retries before giving up on a request.
const REQUEST_RETRY_NUMBER = 12;
// Default wait until next retry in millis.
const REQUEST_RETRY_WAIT = 500;
// Exponential back off for waiting to retry.
const REQUEST_RETRY_WAIT_BACKOFF = 1.5;
/// Keep ids unique across all connections.
let _nextId = 123;
/**
* Client class to interact with the NEAR RPC API.
* @see {@link https://github.com/near/nearcore/tree/master/chain/jsonrpc}
*/ class JsonRpcProvider extends provider_1.Provider {
/**
* @param connectionInfoOrUrl ConnectionInfo or RPC API endpoint URL (deprecated)
*/ constructor(connectionInfoOrUrl){
super();
if (connectionInfoOrUrl != null && typeof connectionInfoOrUrl == "object") this.connection = connectionInfoOrUrl;
else {
const deprecate = depd_1.default("JsonRpcProvider(url?: string)");
deprecate("use `JsonRpcProvider(connectionInfo: ConnectionInfo)` instead");
this.connection = {
url: connectionInfoOrUrl
};
}
}
/**
* Gets the RPC's status
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#general-validator-status}
*/ async status() {
return this.sendJsonRpc("status", []);
}
/**
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await}
*
* @param signedTransaction The signed transaction being sent
*/ async sendTransaction(signedTransaction) {
const bytes = signedTransaction.encode();
return this.sendJsonRpc("broadcast_tx_commit", [
Buffer.from(bytes).toString("base64")
]);
}
/**
* Sends a signed transaction to the RPC and immediately returns transaction hash
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#send-transaction-async)
* @param signedTransaction The signed transaction being sent
* @returns {Promise<FinalExecutionOutcome>}
*/ async sendTransactionAsync(signedTransaction) {
const bytes = signedTransaction.encode();
return this.sendJsonRpc("broadcast_tx_async", [
Buffer.from(bytes).toString("base64")
]);
}
/**
* Gets a transaction's status from the RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#transaction-status}
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
*/ async txStatus(txHash, accountId) {
if (typeof txHash === "string") return this.txStatusString(txHash, accountId);
else return this.txStatusUint8Array(txHash, accountId);
}
async txStatusUint8Array(txHash, accountId) {
return this.sendJsonRpc("tx", [
borsh_1.baseEncode(txHash),
accountId
]);
}
async txStatusString(txHash, accountId) {
return this.sendJsonRpc("tx", [
txHash,
accountId
]);
}
/**
* Gets a transaction's status from the RPC with receipts
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#transaction-status-with-receipts)
* @param txHash The hash of the transaction
* @param accountId The NEAR account that signed the transaction
* @returns {Promise<FinalExecutionOutcome>}
*/ async txStatusReceipts(txHash, accountId) {
return this.sendJsonRpc("EXPERIMENTAL_tx_status", [
borsh_1.baseEncode(txHash),
accountId
]);
}
/**
* Query the RPC as [shown in the docs](https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts)
* Query the RPC by passing an {@link RpcQueryRequest}
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#accounts--contracts}
*
* @typeParam T the shape of the returned query response
*/ async query(...args) {
let result;
if (args.length === 1) result = await this.sendJsonRpc("query", args[0]);
else {
const [path, data] = args;
result = await this.sendJsonRpc("query", [
path,
data
]);
}
if (result && result.error) throw new errors_1.TypedError(`Querying ${args} failed: ${result.error}.\n${JSON.stringify(result, null, 2)}`, rpc_errors_1.getErrorTypeFromErrorMessage(result.error));
return result;
}
/**
* Query for block info from the RPC
* pass block_id OR finality as blockQuery, not both
* @see {@link https://docs.near.org/docs/interaction/rpc#block}
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/ async block(blockQuery) {
const { finality } = blockQuery;
let { blockId } = blockQuery;
if (typeof blockQuery !== "object") {
const deprecate = depd_1.default("JsonRpcProvider.block(blockId)");
deprecate("use `block({ blockId })` or `block({ finality })` instead");
blockId = blockQuery;
}
return this.sendJsonRpc("block", {
block_id: blockId,
finality
});
}
/**
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#block-details)
*/ async blockChanges(blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes_in_block", {
block_id: blockId,
finality
});
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see {@link https://docs.near.org/docs/interaction/rpc#chunk}
*
* @param chunkId Hash of a chunk ID or shard ID
*/ async chunk(chunkId) {
return this.sendJsonRpc("chunk", [
chunkId
]);
}
/**
* Query validators of the epoch defined by the given block id.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#detailed-validator-status}
*
* @param blockId Block hash or height, or null for latest.
*/ async validators(blockId) {
return this.sendJsonRpc("validators", [
blockId
]);
}
/**
* @deprecated
* Gets the genesis config from RPC
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#genesis-config}
*/ async experimental_genesisConfig() {
const deprecate = depd_1.default("JsonRpcProvider.experimental_protocolConfig()");
deprecate("use `experimental_protocolConfig({ sync_checkpoint: 'genesis' })` to fetch the up-to-date or genesis protocol config explicitly");
return await this.sendJsonRpc("EXPERIMENTAL_protocol_config", {
sync_checkpoint: "genesis"
});
}
/**
* Gets the protocol config at a block from RPC
* @see {@link }
*
* @param blockReference specifies the block to get the protocol config for
*/ async experimental_protocolConfig(blockReference) {
return await this.sendJsonRpc("EXPERIMENTAL_protocol_config", blockReference);
}
/**
* @deprecated Use {@link lightClientProof} instead
*/ async experimental_lightClientProof(request) {
const deprecate = depd_1.default("JsonRpcProvider.experimental_lightClientProof(request)");
deprecate("use `lightClientProof` instead");
return await this.lightClientProof(request);
}
/**
* Gets a light client execution proof for verifying execution outcomes
* @see {@link https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof}
*/ async lightClientProof(request) {
return await this.sendJsonRpc("EXPERIMENTAL_light_client_proof", request);
}
/**
* Gets access key changes for a given array of accountIds
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-all)
* @returns {Promise<ChangeResult>}
*/ async accessKeyChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes", {
changes_type: "all_access_key_changes",
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Gets single access key changes for a given array of access keys
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-access-key-changes-single)
* @returns {Promise<ChangeResult>}
*/ async singleAccessKeyChanges(accessKeyArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes", {
changes_type: "single_access_key_changes",
keys: accessKeyArray,
block_id: blockId,
finality
});
}
/**
* Gets account changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-account-changes)
* @returns {Promise<ChangeResult>}
*/ async accountChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes", {
changes_type: "account_changes",
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Gets contract state changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: If you pass a keyPrefix it must be base64 encoded
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-state-changes)
* @returns {Promise<ChangeResult>}
*/ async contractStateChanges(accountIdArray, blockQuery, keyPrefix = "") {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes", {
changes_type: "data_changes",
account_ids: accountIdArray,
key_prefix_base64: keyPrefix,
block_id: blockId,
finality
});
}
/**
* Gets contract code changes for a given array of accountIds
* pass block_id OR finality as blockQuery, not both
* Note: Change is returned in a base64 encoded WASM file
* See [docs for more info](https://docs.near.org/docs/develop/front-end/rpc#view-contract-code-changes)
* @returns {Promise<ChangeResult>}
*/ async contractCodeChanges(accountIdArray, blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("EXPERIMENTAL_changes", {
changes_type: "contract_code_changes",
account_ids: accountIdArray,
block_id: blockId,
finality
});
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#gas-price}
*
* @param blockId Block hash or height, or null for latest.
*/ async gasPrice(blockId) {
return await this.sendJsonRpc("gas_price", [
blockId
]);
}
/**
* Directly call the RPC specifying the method and params
*
* @param method RPC method
* @param params Parameters to the method
*/ async sendJsonRpc(method, params) {
const response = await exponential_backoff_1.default(REQUEST_RETRY_WAIT, REQUEST_RETRY_NUMBER, REQUEST_RETRY_WAIT_BACKOFF, async ()=>{
try {
const request = {
method,
params,
id: _nextId++,
jsonrpc: "2.0"
};
const response = await web_1.fetchJson(this.connection, JSON.stringify(request));
if (response.error) {
if (typeof response.error.data === "object") {
if (typeof response.error.data.error_message === "string" && typeof response.error.data.error_type === "string") // if error data has error_message and error_type properties, we consider that node returned an error in the old format
throw new errors_1.TypedError(response.error.data.error_message, response.error.data.error_type);
throw rpc_errors_1.parseRpcError(response.error.data);
} else {
const errorMessage = `[${response.error.code}] ${response.error.message}: ${response.error.data}`;
// NOTE: All this hackery is happening because structured errors not implemented
// TODO: Fix when https://github.com/nearprotocol/nearcore/issues/1839 gets resolved
if (response.error.data === "Timeout" || errorMessage.includes("Timeout error") || errorMessage.includes("query has timed out")) throw new errors_1.TypedError(errorMessage, "TimeoutError");
throw new errors_1.TypedError(errorMessage, rpc_errors_1.getErrorTypeFromErrorMessage(response.error.data));
}
}
// Success when response.error is not exist
return response;
} catch (error) {
if (error.type === "TimeoutError") {
console.warn(`Retrying request to ${method} as it has timed out`, params);
return null;
}
throw error;
}
});
const { result } = response;
// From jsonrpc spec:
// result
// This member is REQUIRED on success.
// This member MUST NOT exist if there was an error invoking the method.
if (typeof result === "undefined") throw new errors_1.TypedError(`Exceeded ${REQUEST_RETRY_NUMBER} attempts for request to ${method}.`, "RetriesExceeded");
return result;
}
}
exports.JsonRpcProvider = JsonRpcProvider;
},{"buffer":"dvCeB","depd":"2jGeI","./provider":"cUEh0","../utils/web":"iSqiB","../utils/errors":"btMYy","borsh":"4JCmN","../utils/exponential-backoff":"51I5X","../utils/rpc_errors":"1TB1L"}],"2jGeI":[function(require,module,exports) {
/*!
* depd
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/ "use strict";
/**
* Module exports.
* @public
*/ module.exports = depd;
/**
* Create deprecate for namespace in caller.
*/ function depd(namespace) {
if (!namespace) throw new TypeError("argument namespace is required");
function deprecate(message) {
// no-op in browser
}
deprecate._file = undefined;
deprecate._ignored = true;
deprecate._namespace = namespace;
deprecate._traced = false;
deprecate._warned = Object.create(null);
deprecate.function = wrapfunction;
deprecate.property = wrapproperty;
return deprecate;
}
/**
* Return a wrapped function in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/ function wrapfunction(fn, message) {
if (typeof fn !== "function") throw new TypeError("argument fn must be a function");
return fn;
}
/**
* Wrap property in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/ function wrapproperty(obj, prop, message) {
if (!obj || typeof obj !== "object" && typeof obj !== "function") throw new TypeError("argument obj must be object");
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
if (!descriptor) throw new TypeError("must call property on owner object");
if (!descriptor.configurable) throw new TypeError("property must be configurable");
}
},{}],"iSqiB":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fetchJson = void 0;
const http_errors_1 = __importDefault(require("http-errors"));
const exponential_backoff_1 = __importDefault(require("./exponential-backoff"));
const providers_1 = require("../providers");
const errors_1 = require("./errors");
const START_WAIT_TIME_MS = 1000;
const BACKOFF_MULTIPLIER = 1.5;
const RETRY_NUMBER = 10;
async function fetchJson(connectionInfoOrUrl, json) {
let connectionInfo = {
url: null
};
if (typeof connectionInfoOrUrl === "string") connectionInfo.url = connectionInfoOrUrl;
else connectionInfo = connectionInfoOrUrl;
const response = await exponential_backoff_1.default(START_WAIT_TIME_MS, RETRY_NUMBER, BACKOFF_MULTIPLIER, async ()=>{
try {
const response = await fetch(connectionInfo.url, {
method: json ? "POST" : "GET",
body: json ? json : undefined,
headers: {
...connectionInfo.headers,
"Content-Type": "application/json"
}
});
if (!response.ok) {
if (response.status === 503) {
errors_1.logWarning(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`);
return null;
}
throw http_errors_1.default(response.status, await response.text());
}
return response;
} catch (error) {
if (error.toString().includes("FetchError") || error.toString().includes("Failed to fetch")) {
errors_1.logWarning(`Retrying HTTP request for ${connectionInfo.url} because of error: ${error}`);
return null;
}
throw error;
}
});
if (!response) throw new providers_1.TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${connectionInfo.url}.`, "RetriesExceeded");
return await response.json();
}
exports.fetchJson = fetchJson;
},{"http-errors":"a3NQ3","./exponential-backoff":"51I5X","../providers":"gtL2a","./errors":"btMYy"}],"a3NQ3":[function(require,module,exports) {
/*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/ "use strict";
/**
* Module dependencies.
* @private
*/ var deprecate = require("depd")("http-errors");
var setPrototypeOf = require("setprototypeof");
var statuses = require("statuses");
var inherits = require("inherits");
var toIdentifier = require("toidentifier");
/**
* Module exports.
* @public
*/ module.exports = createError;
module.exports.HttpError = createHttpErrorConstructor();
module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError);
// Populate exports for all constructors
populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError);
/**
* Get the code class of a status code.
* @private
*/ function codeClass(status) {
return Number(String(status).charAt(0) + "00");
}
/**
* Create a new HTTP Error.
*
* @returns {Error}
* @public
*/ function createError() {
// so much arity going on ~_~
var err;
var msg;
var status = 500;
var props = {};
for(var i = 0; i < arguments.length; i++){
var arg = arguments[i];
if (arg instanceof Error) {
err = arg;
status = err.status || err.statusCode || status;
continue;
}
switch(typeof arg){
case "string":
msg = arg;
break;
case "number":
status = arg;
if (i !== 0) deprecate("non-first-argument status code; replace with createError(" + arg + ", ...)");
break;
case "object":
props = arg;
break;
}
}
if (typeof status === "number" && (status < 400 || status >= 600)) deprecate("non-error status code; use only 4xx or 5xx status codes");
if (typeof status !== "number" || !statuses[status] && (status < 400 || status >= 600)) status = 500;
// constructor
var HttpError = createError[status] || createError[codeClass(status)];
if (!err) {
// create error
err = HttpError ? new HttpError(msg) : new Error(msg || statuses[status]);
Error.captureStackTrace(err, createError);
}
if (!HttpError || !(err instanceof HttpError) || err.status !== status) {
// add properties to generic error
err.expose = status < 500;
err.status = err.statusCode = status;
}
for(var key in props)if (key !== "status" && key !== "statusCode") err[key] = props[key];
return err;
}
/**
* Create HTTP error abstract base class.
* @private
*/ function createHttpErrorConstructor() {
function HttpError() {
throw new TypeError("cannot construct abstract class");
}
inherits(HttpError, Error);
return HttpError;
}
/**
* Create a constructor for a client error.
* @private
*/ function createClientErrorConstructor(HttpError, name, code) {
var className = toClassName(name);
function ClientError(message) {
// create the error object
var msg = message != null ? message : statuses[code];
var err = new Error(msg);
// capture a stack trace to the construction point
Error.captureStackTrace(err, ClientError);
// adjust the [[Prototype]]
setPrototypeOf(err, ClientError.prototype);
// redefine the error message
Object.defineProperty(err, "message", {
enumerable: true,
configurable: true,
value: msg,
writable: true
});
// redefine the error name
Object.defineProperty(err, "name", {
enumerable: false,
configurable: true,
value: className,
writable: true
});
return err;
}
inherits(ClientError, HttpError);
nameFunc(ClientError, className);
ClientError.prototype.status = code;
ClientError.prototype.statusCode = code;
ClientError.prototype.expose = true;
return ClientError;
}
/**
* Create function to test is a value is a HttpError.
* @private
*/ function createIsHttpErrorFunction(HttpError) {
return function isHttpError(val) {
if (!val || typeof val !== "object") return false;
if (val instanceof HttpError) return true;
return val instanceof Error && typeof val.expose === "boolean" && typeof val.statusCode === "number" && val.status === val.statusCode;
};
}
/**
* Create a constructor for a server error.
* @private
*/ function createServerErrorConstructor(HttpError, name, code) {
var className = toClassName(name);
function ServerError(message) {
// create the error object
var msg = message != null ? message : statuses[code];
var err = new Error(msg);
// capture a stack trace to the construction point
Error.captureStackTrace(err, ServerError);
// adjust the [[Prototype]]
setPrototypeOf(err, ServerError.prototype);
// redefine the error message
Object.defineProperty(err, "message", {
enumerable: true,
configurable: true,
value: msg,
writable: true
});
// redefine the error name
Object.defineProperty(err, "name", {
enumerable: false,
configurable: true,
value: className,
writable: true
});
return err;
}
inherits(ServerError, HttpError);
nameFunc(ServerError, className);
ServerError.prototype.status = code;
ServerError.prototype.statusCode = code;
ServerError.prototype.expose = false;
return ServerError;
}
/**
* Set the name of a function, if possible.
* @private
*/ function nameFunc(func, name) {
var desc = Object.getOwnPropertyDescriptor(func, "name");
if (desc && desc.configurable) {
desc.value = name;
Object.defineProperty(func, "name", desc);
}
}
/**
* Populate the exports object with constructors for every error class.
* @private
*/ function populateConstructorExports(exports, codes, HttpError) {
codes.forEach(function forEachCode(code) {
var CodeError;
var name = toIdentifier(statuses[code]);
switch(codeClass(code)){
case 400:
CodeError = createClientErrorConstructor(HttpError, name, code);
break;
case 500:
CodeError = createServerErrorConstructor(HttpError, name, code);
break;
}
if (CodeError) {
// export the constructor
exports[code] = CodeError;
exports[name] = CodeError;
}
});
// backwards-compatibility
exports["I'mateapot"] = deprecate.function(exports.ImATeapot, '"I\'mateapot"; use "ImATeapot" instead');
}
/**
* Get a class name from a name identifier.
* @private
*/ function toClassName(name) {
return name.substr(-5) !== "Error" ? name + "Error" : name;
}
},{"depd":"hArTA","setprototypeof":"7xKC9","statuses":"l1u37","inherits":"bRL3M","toidentifier":"gn15y"}],"hArTA":[function(require,module,exports) {
/*!
* depd
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/ "use strict";
/**
* Module exports.
* @public
*/ module.exports = depd;
/**
* Create deprecate for namespace in caller.
*/ function depd(namespace) {
if (!namespace) throw new TypeError("argument namespace is required");
function deprecate(message) {
// no-op in browser
}
deprecate._file = undefined;
deprecate._ignored = true;
deprecate._namespace = namespace;
deprecate._traced = false;
deprecate._warned = Object.create(null);
deprecate.function = wrapfunction;
deprecate.property = wrapproperty;
return deprecate;
}
/**
* Return a wrapped function in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/ function wrapfunction(fn, message) {
if (typeof fn !== "function") throw new TypeError("argument fn must be a function");
return fn;
}
/**
* Wrap property in a deprecation message.
*
* This is a no-op version of the wrapper, which does nothing but call
* validation.
*/ function wrapproperty(obj, prop, message) {
if (!obj || typeof obj !== "object" && typeof obj !== "function") throw new TypeError("argument obj must be object");
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
if (!descriptor) throw new TypeError("must call property on owner object");
if (!descriptor.configurable) throw new TypeError("property must be configurable");
}
},{}],"7xKC9":[function(require,module,exports) {
"use strict";
/* eslint no-proto: 0 */ module.exports = Object.setPrototypeOf || (({
__proto__: []
}) instanceof Array ? setProtoOf : mixinProperties);
function setProtoOf(obj, proto) {
obj.__proto__ = proto;
return obj;
}
function mixinProperties(obj, proto) {
for(var prop in proto)if (!Object.prototype.hasOwnProperty.call(obj, prop)) obj[prop] = proto[prop];
return obj;
}
},{}],"l1u37":[function(require,module,exports) {
/*!
* statuses
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/ "use strict";
/**
* Module dependencies.
* @private
*/ var codes = require("./codes.json");
/**
* Module exports.
* @public
*/ module.exports = status;
// status code to message map
status.STATUS_CODES = codes;
// array of status codes
status.codes = populateStatusesMap(status, codes);
// status codes for redirects
status.redirect = {
300: true,
301: true,
302: true,
303: true,
305: true,
307: true,
308: true
};
// status codes for empty bodies
status.empty = {
204: true,
205: true,
304: true
};
// status codes for when you should retry the request
status.retry = {
502: true,
503: true,
504: true
};
/**
* Populate the statuses map for given codes.
* @private
*/ function populateStatusesMap(statuses, codes) {
var arr = [];
Object.keys(codes).forEach(function forEachCode(code) {
var message = codes[code];
var status = Number(code);
// Populate properties
statuses[status] = message;
statuses[message] = status;
statuses[message.toLowerCase()] = status;
// Add to array
arr.push(status);
});
return arr;
}
/**
* Get the status code.
*
* Given a number, this will throw if it is not a known status
* code, otherwise the code will be returned. Given a string,
* the string will be parsed for a number and return the code
* if valid, otherwise will lookup the code assuming this is
* the status message.
*
* @param {string|number} code
* @returns {number}
* @public
*/ function status(code) {
if (typeof code === "number") {
if (!status[code]) throw new Error("invalid status code: " + code);
return code;
}
if (typeof code !== "string") throw new TypeError("code must be a number or string");
// '403'
var n = parseInt(code, 10);
if (!isNaN(n)) {
if (!status[n]) throw new Error("invalid status code: " + n);
return n;
}
n = status[code.toLowerCase()];
if (!n) throw new Error('invalid status message: "' + code + '"');
return n;
}
},{"./codes.json":"8IptR"}],"8IptR":[function(require,module,exports) {
module.exports = JSON.parse('{"100":"Continue","101":"Switching Protocols","102":"Processing","103":"Early Hints","200":"OK","201":"Created","202":"Accepted","203":"Non-Authoritative Information","204":"No Content","205":"Reset Content","206":"Partial Content","207":"Multi-Status","208":"Already Reported","226":"IM Used","300":"Multiple Choices","301":"Moved Permanently","302":"Found","303":"See Other","304":"Not Modified","305":"Use Proxy","306":"(Unused)","307":"Temporary Redirect","308":"Permanent Redirect","400":"Bad Request","401":"Unauthorized","402":"Payment Required","403":"Forbidden","404":"Not Found","405":"Method Not Allowed","406":"Not Acceptable","407":"Proxy Authentication Required","408":"Request Timeout","409":"Conflict","410":"Gone","411":"Length Required","412":"Precondition Failed","413":"Payload Too Large","414":"URI Too Long","415":"Unsupported Media Type","416":"Range Not Satisfiable","417":"Expectation Failed","418":"I\'m a teapot","421":"Misdirected Request","422":"Unprocessable Entity","423":"Locked","424":"Failed Dependency","425":"Unordered Collection","426":"Upgrade Required","428":"Precondition Required","429":"Too Many Requests","431":"Request Header Fields Too Large","451":"Unavailable For Legal Reasons","500":"Internal Server Error","501":"Not Implemented","502":"Bad Gateway","503":"Service Unavailable","504":"Gateway Timeout","505":"HTTP Version Not Supported","506":"Variant Also Negotiates","507":"Insufficient Storage","508":"Loop Detected","509":"Bandwidth Limit Exceeded","510":"Not Extended","511":"Network Authentication Required"}');
},{}],"bRL3M":[function(require,module,exports) {
if (typeof Object.create === "function") // implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
};
else // old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
var TempCtor = function() {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
};
},{}],"gn15y":[function(require,module,exports) {
/*!
* toidentifier
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/ "use strict";
/**
* Module exports.
* @public
*/ module.exports = toIdentifier;
/**
* Trasform the given string into a JavaScript identifier
*
* @param {string} str
* @returns {string}
* @public
*/ function toIdentifier(str) {
return str.split(" ").map(function(token) {
return token.slice(0, 1).toUpperCase() + token.slice(1);
}).join("").replace(/[^ _0-9a-z]/gi, "");
}
},{}],"51I5X":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
async function exponentialBackoff(startWaitTime, retryNumber, waitBackoff, getResult) {
// TODO: jitter?
let waitTime = startWaitTime;
for(let i = 0; i < retryNumber; i++){
const result = await getResult();
if (result) return result;
await sleep(waitTime);
waitTime *= waitBackoff;
}
return null;
}
exports.default = exponentialBackoff;
// Sleep given number of millis.
function sleep(millis) {
return new Promise((resolve)=>setTimeout(resolve, millis));
}
},{}],"btMYy":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.logWarning = exports.ErrorContext = exports.TypedError = exports.ArgumentTypeError = exports.PositionalArgsError = void 0;
class PositionalArgsError extends Error {
constructor(){
super("Contract method calls expect named arguments wrapped in object, e.g. { argName1: argValue1, argName2: argValue2 }");
}
}
exports.PositionalArgsError = PositionalArgsError;
class ArgumentTypeError extends Error {
constructor(argName, argType, argValue){
super(`Expected ${argType} for '${argName}' argument, but got '${JSON.stringify(argValue)}'`);
}
}
exports.ArgumentTypeError = ArgumentTypeError;
class TypedError extends Error {
constructor(message, type, context){
super(message);
this.type = type || "UntypedError";
this.context = context;
}
}
exports.TypedError = TypedError;
class ErrorContext {
constructor(transactionHash){
this.transactionHash = transactionHash;
}
}
exports.ErrorContext = ErrorContext;
function logWarning(...args) {
console.warn(...args);
}
exports.logWarning = logWarning;
},{}],"1TB1L":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getErrorTypeFromErrorMessage = exports.formatError = exports.parseResultError = exports.parseRpcError = exports.ServerError = void 0;
const mustache_1 = __importDefault(require("mustache"));
const rpc_error_schema_json_1 = __importDefault(require("../generated/rpc_error_schema.json"));
const error_messages_json_1 = __importDefault(require("../res/error_messages.json"));
const common_index_1 = require("../common-index");
const errors_1 = require("../utils/errors");
const mustacheHelpers = {
formatNear: ()=>(n, render)=>common_index_1.utils.format.formatNearAmount(render(n))
};
class ServerError extends errors_1.TypedError {
}
exports.ServerError = ServerError;
class ServerTransactionError extends ServerError {
}
function parseRpcError(errorObj) {
const result = {};
const errorClassName = walkSubtype(errorObj, rpc_error_schema_json_1.default.schema, result, "");
// NOTE: This assumes that all errors extend TypedError
const error = new ServerError(formatError(errorClassName, result), errorClassName);
Object.assign(error, result);
return error;
}
exports.parseRpcError = parseRpcError;
function parseResultError(result) {
const server_error = parseRpcError(result.status.Failure);
const server_tx_error = new ServerTransactionError();
Object.assign(server_tx_error, server_error);
server_tx_error.type = server_error.type;
server_tx_error.message = server_error.message;
server_tx_error.transaction_outcome = result.transaction_outcome;
return server_tx_error;
}
exports.parseResultError = parseResultError;
function formatError(errorClassName, errorData) {
if (typeof error_messages_json_1.default[errorClassName] === "string") return mustache_1.default.render(error_messages_json_1.default[errorClassName], {
...errorData,
...mustacheHelpers
});
return JSON.stringify(errorData);
}
exports.formatError = formatError;
/**
* Walks through defined schema returning error(s) recursively
* @param errorObj The error to be parsed
* @param schema A defined schema in JSON mapping to the RPC errors
* @param result An object used in recursion or called directly
* @param typeName The human-readable error type name as defined in the JSON mapping
*/ function walkSubtype(errorObj, schema, result, typeName) {
let error;
let type;
let errorTypeName;
for(const errorName in schema){
if (isString(errorObj[errorName])) // Return early if error type is in a schema
return errorObj[errorName];
if (isObject(errorObj[errorName])) {
error = errorObj[errorName];
type = schema[errorName];
errorTypeName = errorName;
} else if (isObject(errorObj.kind) && isObject(errorObj.kind[errorName])) {
error = errorObj.kind[errorName];
type = schema[errorName];
errorTypeName = errorName;
} else continue;
}
if (error && type) {
for (const prop of Object.keys(type.props))result[prop] = error[prop];
return walkSubtype(error, schema, result, errorTypeName);
} else {
// TODO: is this the right thing to do?
result.kind = errorObj;
return typeName;
}
}
function getErrorTypeFromErrorMessage(errorMessage) {
// This function should be removed when JSON RPC starts returning typed errors.
switch(true){
case /^account .*? does not exist while viewing$/.test(errorMessage):
return "AccountDoesNotExist";
case /^Account .*? doesn't exist$/.test(errorMessage):
return "AccountDoesNotExist";
case /^access key .*? does not exist while viewing$/.test(errorMessage):
return "AccessKeyDoesNotExist";
case /wasm execution failed with error: FunctionCallError\(CompilationError\(CodeDoesNotExist/.test(errorMessage):
return "CodeDoesNotExist";
case /Transaction nonce \d+ must be larger than nonce of the used access key \d+/.test(errorMessage):
return "InvalidNonce";
default:
return "UntypedError";
}
}
exports.getErrorTypeFromErrorMessage = getErrorTypeFromErrorMessage;
/**
* Helper function determining if the argument is an object
* @param n Value to check
*/ function isObject(n) {
return Object.prototype.toString.call(n) === "[object Object]";
}
/**
* Helper function determining if the argument is a string
* @param n Value to check
*/ function isString(n) {
return Object.prototype.toString.call(n) === "[object String]";
}
},{"mustache":"izE6r","../generated/rpc_error_schema.json":"k81HS","../res/error_messages.json":"1Z5Hy","../common-index":"gtZXS","../utils/errors":"btMYy"}],"izE6r":[function(require,module,exports) {
(function(global, factory) {
module.exports = factory();
})(this, function() {
"use strict";
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/ var objectToString = Object.prototype.toString;
var isArray = Array.isArray || function isArrayPolyfill(object) {
return objectToString.call(object) === "[object Array]";
};
function isFunction(object) {
return typeof object === "function";
}
/**
* More correct typeof string handling array
* which normally returns typeof 'object'
*/ function typeStr(obj) {
return isArray(obj) ? "array" : typeof obj;
}
function escapeRegExp(string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
/**
* Null safe way of checking whether or not an object,
* including its prototype, has a given property
*/ function hasProperty(obj, propName) {
return obj != null && typeof obj === "object" && propName in obj;
}
/**
* Safe way of detecting whether or not the given thing is a primitive and
* whether it has the given property
*/ function primitiveHasOwnProperty(primitive, propName) {
return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName);
}
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
var regExpTest = RegExp.prototype.test;
function testRegExp(re, string) {
return regExpTest.call(re, string);
}
var nonSpaceRe = /\S/;
function isWhitespace(string) {
return !testRegExp(nonSpaceRe, string);
}
var entityMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
"/": "&#x2F;",
"`": "&#x60;",
"=": "&#x3D;"
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) {
return entityMap[s];
});
}
var whiteRe = /\s*/;
var spaceRe = /\s+/;
var equalsRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*
* Tokens for partials also contain two more elements: 1) a string value of
* indendation prior to that tag and 2) the index of that tag on that line -
* eg a value of 2 indicates the partial is the third tag on this line.
*/ function parseTemplate(template, tags) {
if (!template) return [];
var lineHasNonSpace = false;
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
var hasTag = false; // Is there a {{tag}} on the current line?
var nonSpace = false; // Is there a non-space char on the current line?
var indentation = ""; // Tracks indentation for tags that use it
var tagIndex = 0; // Stores a count of number of tags encountered on a line
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
function stripSpace() {
if (hasTag && !nonSpace) while(spaces.length)delete tokens[spaces.pop()];
else spaces = [];
hasTag = false;
nonSpace = false;
}
var openingTagRe, closingTagRe, closingCurlyRe;
function compileTags(tagsToCompile) {
if (typeof tagsToCompile === "string") tagsToCompile = tagsToCompile.split(spaceRe, 2);
if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) throw new Error("Invalid tags: " + tagsToCompile);
openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*");
closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1]));
closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1]));
}
compileTags(tags || mustache.tags);
var scanner = new Scanner(template);
var start, type, value, chr, token, openSection;
while(!scanner.eos()){
start = scanner.pos;
// Match any text between tags.
value = scanner.scanUntil(openingTagRe);
if (value) for(var i = 0, valueLength = value.length; i < valueLength; ++i){
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
indentation += chr;
} else {
nonSpace = true;
lineHasNonSpace = true;
indentation += " ";
}
tokens.push([
"text",
chr,
start,
start + 1
]);
start += 1;
// Check for whitespace on the current line.
if (chr === "\n") {
stripSpace();
indentation = "";
tagIndex = 0;
lineHasNonSpace = false;
}
}
// Match the opening tag.
if (!scanner.scan(openingTagRe)) break;
hasTag = true;
// Get the tag type.
type = scanner.scan(tagRe) || "name";
scanner.scan(whiteRe);
// Get the tag value.
if (type === "=") {
value = scanner.scanUntil(equalsRe);
scanner.scan(equalsRe);
scanner.scanUntil(closingTagRe);
} else if (type === "{") {
value = scanner.scanUntil(closingCurlyRe);
scanner.scan(curlyRe);
scanner.scanUntil(closingTagRe);
type = "&";
} else value = scanner.scanUntil(closingTagRe);
// Match the closing tag.
if (!scanner.scan(closingTagRe)) throw new Error("Unclosed tag at " + scanner.pos);
if (type == ">") token = [
type,
value,
start,
scanner.pos,
indentation,
tagIndex,
lineHasNonSpace
];
else token = [
type,
value,
start,
scanner.pos
];
tagIndex++;
tokens.push(token);
if (type === "#" || type === "^") sections.push(token);
else if (type === "/") {
// Check section nesting.
openSection = sections.pop();
if (!openSection) throw new Error('Unopened section "' + value + '" at ' + start);
if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
} else if (type === "name" || type === "{" || type === "&") nonSpace = true;
else if (type === "=") // Set the tags for the next time around.
compileTags(value);
}
stripSpace();
// Make sure there are no open sections when we're done.
openSection = sections.pop();
if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
return nestTokens(squashTokens(tokens));
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/ function squashTokens(tokens) {
var squashedTokens = [];
var token, lastToken;
for(var i = 0, numTokens = tokens.length; i < numTokens; ++i){
token = tokens[i];
if (token) {
if (token[0] === "text" && lastToken && lastToken[0] === "text") {
lastToken[1] += token[1];
lastToken[3] = token[3];
} else {
squashedTokens.push(token);
lastToken = token;
}
}
}
return squashedTokens;
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/ function nestTokens(tokens) {
var nestedTokens = [];
var collector = nestedTokens;
var sections = [];
var token, section;
for(var i = 0, numTokens = tokens.length; i < numTokens; ++i){
token = tokens[i];
switch(token[0]){
case "#":
case "^":
collector.push(token);
sections.push(token);
collector = token[4] = [];
break;
case "/":
section = sections.pop();
section[5] = token[2];
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
break;
default:
collector.push(token);
}
}
return nestedTokens;
}
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
*/ function Scanner(string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
*/ Scanner.prototype.eos = function eos() {
return this.tail === "";
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/ Scanner.prototype.scan = function scan(re) {
var match = this.tail.match(re);
if (!match || match.index !== 0) return "";
var string = match[0];
this.tail = this.tail.substring(string.length);
this.pos += string.length;
return string;
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/ Scanner.prototype.scanUntil = function scanUntil(re) {
var index = this.tail.search(re), match;
switch(index){
case -1:
match = this.tail;
this.tail = "";
break;
case 0:
match = "";
break;
default:
match = this.tail.substring(0, index);
this.tail = this.tail.substring(index);
}
this.pos += match.length;
return match;
};
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
*/ function Context(view, parentContext) {
this.view = view;
this.cache = {
".": this.view
};
this.parent = parentContext;
}
/**
* Creates a new context using the given view with this context
* as the parent.
*/ Context.prototype.push = function push(view) {
return new Context(view, this);
};
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
*/ Context.prototype.lookup = function lookup(name) {
var cache1 = this.cache;
var value;
if (cache1.hasOwnProperty(name)) value = cache1[name];
else {
var context = this, intermediateValue, names, index, lookupHit = false;
while(context){
if (name.indexOf(".") > 0) {
intermediateValue = context.view;
names = name.split(".");
index = 0;
/**
* Using the dot notion path in `name`, we descend through the
* nested objects.
*
* To be certain that the lookup has been successful, we have to
* check if the last object in the path actually has the property
* we are looking for. We store the result in `lookupHit`.
*
* This is specially necessary for when the value has been set to
* `undefined` and we want to avoid looking up parent contexts.
*
* In the case where dot notation is used, we consider the lookup
* to be successful even if the last "object" in the path is
* not actually an object but a primitive (e.g., a string, or an
* integer), because it is sometimes useful to access a property
* of an autoboxed primitive, such as the length of a string.
**/ while(intermediateValue != null && index < names.length){
if (index === names.length - 1) lookupHit = hasProperty(intermediateValue, names[index]) || primitiveHasOwnProperty(intermediateValue, names[index]);
intermediateValue = intermediateValue[names[index++]];
}
} else {
intermediateValue = context.view[name];
/**
* Only checking against `hasProperty`, which always returns `false` if
* `context.view` is not an object. Deliberately omitting the check
* against `primitiveHasOwnProperty` if dot notation is not used.
*
* Consider this example:
* ```
* Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
* ```
*
* If we were to check also against `primitiveHasOwnProperty`, as we do
* in the dot notation case, then render call would return:
*
* "The length of a football field is 9."
*
* rather than the expected:
*
* "The length of a football field is 100 yards."
**/ lookupHit = hasProperty(context.view, name);
}
if (lookupHit) {
value = intermediateValue;
break;
}
context = context.parent;
}
cache1[name] = value;
}
if (isFunction(value)) value = value.call(this.view);
return value;
};
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
*/ function Writer() {
this.templateCache = {
_cache: {},
set: function set(key, value) {
this._cache[key] = value;
},
get: function get(key) {
return this._cache[key];
},
clear: function clear() {
this._cache = {};
}
};
}
/**
* Clears all cached templates in this writer.
*/ Writer.prototype.clearCache = function clearCache() {
if (typeof this.templateCache !== "undefined") this.templateCache.clear();
};
/**
* Parses and caches the given `template` according to the given `tags` or
* `mustache.tags` if `tags` is omitted, and returns the array of tokens
* that is generated from the parse.
*/ Writer.prototype.parse = function parse(template, tags) {
var cache1 = this.templateCache;
var cacheKey = template + ":" + (tags || mustache.tags).join(":");
var isCacheEnabled = typeof cache1 !== "undefined";
var tokens = isCacheEnabled ? cache1.get(cacheKey) : undefined;
if (tokens == undefined) {
tokens = parseTemplate(template, tags);
isCacheEnabled && cache1.set(cacheKey, tokens);
}
return tokens;
};
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
*
* If the optional `config` argument is given here, then it should be an
* object with a `tags` attribute or an `escape` attribute or both.
* If an array is passed, then it will be interpreted the same way as
* a `tags` attribute on a `config` object.
*
* The `tags` attribute of a `config` object must be an array with two
* string values: the opening and closing tags used in the template (e.g.
* [ "<%", "%>" ]). The default is to mustache.tags.
*
* The `escape` attribute of a `config` object must be a function which
* accepts a string as input and outputs a safely escaped string.
* If an `escape` function is not provided, then an HTML-safe string
* escaping function is used as the default.
*/ Writer.prototype.render = function render(template, view, partials, config) {
var tags = this.getConfigTags(config);
var tokens = this.parse(template, tags);
var context = view instanceof Context ? view : new Context(view, undefined);
return this.renderTokens(tokens, context, partials, template, config);
};
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
*/ Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config) {
var buffer = "";
var token, symbol, value;
for(var i = 0, numTokens = tokens.length; i < numTokens; ++i){
value = undefined;
token = tokens[i];
symbol = token[0];
if (symbol === "#") value = this.renderSection(token, context, partials, originalTemplate, config);
else if (symbol === "^") value = this.renderInverted(token, context, partials, originalTemplate, config);
else if (symbol === ">") value = this.renderPartial(token, context, partials, config);
else if (symbol === "&") value = this.unescapedValue(token, context);
else if (symbol === "name") value = this.escapedValue(token, context, config);
else if (symbol === "text") value = this.rawValue(token);
if (value !== undefined) buffer += value;
}
return buffer;
};
Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config) {
var self = this;
var buffer = "";
var value = context.lookup(token[1]);
// This function is used to render an arbitrary template
// in the current context by higher-order sections.
function subRender(template) {
return self.render(template, context, partials, config);
}
if (!value) return;
if (isArray(value)) for(var j = 0, valueLength = value.length; j < valueLength; ++j)buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);
else if (typeof value === "object" || typeof value === "string" || typeof value === "number") buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
else if (isFunction(value)) {
if (typeof originalTemplate !== "string") throw new Error("Cannot use higher-order sections without the original template");
// Extract the portion of the original template that the section contains.
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
if (value != null) buffer += value;
} else buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
return buffer;
};
Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config) {
var value = context.lookup(token[1]);
// Use JavaScript's definition of falsy. Include empty arrays.
// See https://github.com/janl/mustache.js/issues/186
if (!value || isArray(value) && value.length === 0) return this.renderTokens(token[4], context, partials, originalTemplate, config);
};
Writer.prototype.indentPartial = function indentPartial(partial, indentation, lineHasNonSpace) {
var filteredIndentation = indentation.replace(/[^ \t]/g, "");
var partialByNl = partial.split("\n");
for(var i = 0; i < partialByNl.length; i++)if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) partialByNl[i] = filteredIndentation + partialByNl[i];
return partialByNl.join("\n");
};
Writer.prototype.renderPartial = function renderPartial(token, context, partials, config) {
if (!partials) return;
var tags = this.getConfigTags(config);
var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
if (value != null) {
var lineHasNonSpace = token[6];
var tagIndex = token[5];
var indentation = token[4];
var indentedValue = value;
if (tagIndex == 0 && indentation) indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
var tokens = this.parse(indentedValue, tags);
return this.renderTokens(tokens, context, partials, indentedValue, config);
}
};
Writer.prototype.unescapedValue = function unescapedValue(token, context) {
var value = context.lookup(token[1]);
if (value != null) return value;
};
Writer.prototype.escapedValue = function escapedValue(token, context, config) {
var escape = this.getConfigEscape(config) || mustache.escape;
var value = context.lookup(token[1]);
if (value != null) return typeof value === "number" && escape === mustache.escape ? String(value) : escape(value);
};
Writer.prototype.rawValue = function rawValue(token) {
return token[1];
};
Writer.prototype.getConfigTags = function getConfigTags(config) {
if (isArray(config)) return config;
else if (config && typeof config === "object") return config.tags;
else return undefined;
};
Writer.prototype.getConfigEscape = function getConfigEscape(config) {
if (config && typeof config === "object" && !isArray(config)) return config.escape;
else return undefined;
};
var mustache = {
name: "mustache.js",
version: "4.2.0",
tags: [
"{{",
"}}"
],
clearCache: undefined,
escape: undefined,
parse: undefined,
render: undefined,
Scanner: undefined,
Context: undefined,
Writer: undefined,
/**
* Allows a user to override the default caching strategy, by providing an
* object with set, get and clear methods. This can also be used to disable
* the cache by setting it to the literal `undefined`.
*/ set templateCache (cache){
defaultWriter.templateCache = cache;
},
/**
* Gets the default or overridden caching object from the default writer.
*/ get templateCache () {
return defaultWriter.templateCache;
}
};
// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();
/**
* Clears all cached templates in the default writer.
*/ mustache.clearCache = function clearCache() {
return defaultWriter.clearCache();
};
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
*/ mustache.parse = function parse(template, tags) {
return defaultWriter.parse(template, tags);
};
/**
* Renders the `template` with the given `view`, `partials`, and `config`
* using the default writer.
*/ mustache.render = function render(template, view, partials, config) {
if (typeof template !== "string") throw new TypeError('Invalid template! Template should be a "string" but "' + typeStr(template) + '" was given as the first ' + "argument for mustache#render(template, view, partials)");
return defaultWriter.render(template, view, partials, config);
};
// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
mustache.escape = escapeHtml;
// Export these mainly for testing, but also for advanced usage.
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;
return mustache;
});
},{}],"k81HS":[function(require,module,exports) {
module.exports = JSON.parse('{"schema":{"BadUTF16":{"name":"BadUTF16","subtypes":[],"props":{}},"BadUTF8":{"name":"BadUTF8","subtypes":[],"props":{}},"BalanceExceeded":{"name":"BalanceExceeded","subtypes":[],"props":{}},"BreakpointTrap":{"name":"BreakpointTrap","subtypes":[],"props":{}},"CacheError":{"name":"CacheError","subtypes":["ReadError","WriteError","DeserializationError","SerializationError"],"props":{}},"CallIndirectOOB":{"name":"CallIndirectOOB","subtypes":[],"props":{}},"CannotAppendActionToJointPromise":{"name":"CannotAppendActionToJointPromise","subtypes":[],"props":{}},"CannotReturnJointPromise":{"name":"CannotReturnJointPromise","subtypes":[],"props":{}},"CodeDoesNotExist":{"name":"CodeDoesNotExist","subtypes":[],"props":{"account_id":""}},"CompilationError":{"name":"CompilationError","subtypes":["CodeDoesNotExist","PrepareError","WasmerCompileError"],"props":{}},"ContractSizeExceeded":{"name":"ContractSizeExceeded","subtypes":[],"props":{"limit":"","size":""}},"Deprecated":{"name":"Deprecated","subtypes":[],"props":{"method_name":""}},"Deserialization":{"name":"Deserialization","subtypes":[],"props":{}},"DeserializationError":{"name":"DeserializationError","subtypes":[],"props":{}},"EmptyMethodName":{"name":"EmptyMethodName","subtypes":[],"props":{}},"FunctionCallError":{"name":"FunctionCallError","subtypes":["CompilationError","LinkError","MethodResolveError","WasmTrap","WasmUnknownError","HostError","EvmError"],"props":{}},"GasExceeded":{"name":"GasExceeded","subtypes":[],"props":{}},"GasInstrumentation":{"name":"GasInstrumentation","subtypes":[],"props":{}},"GasLimitExceeded":{"name":"GasLimitExceeded","subtypes":[],"props":{}},"GenericTrap":{"name":"GenericTrap","subtypes":[],"props":{}},"GuestPanic":{"name":"GuestPanic","subtypes":[],"props":{"panic_msg":""}},"HostError":{"name":"HostError","subtypes":["BadUTF16","BadUTF8","GasExceeded","GasLimitExceeded","BalanceExceeded","EmptyMethodName","GuestPanic","IntegerOverflow","InvalidPromiseIndex","CannotAppendActionToJointPromise","CannotReturnJointPromise","InvalidPromiseResultIndex","InvalidRegisterId","IteratorWasInvalidated","MemoryAccessViolation","InvalidReceiptIndex","InvalidIteratorIndex","InvalidAccountId","InvalidMethodName","InvalidPublicKey","ProhibitedInView","NumberOfLogsExceeded","KeyLengthExceeded","ValueLengthExceeded","TotalLogLengthExceeded","NumberPromisesExceeded","NumberInputDataDependenciesExceeded","ReturnedValueLengthExceeded","ContractSizeExceeded","Deprecated"],"props":{}},"IllegalArithmetic":{"name":"IllegalArithmetic","subtypes":[],"props":{}},"IncorrectCallIndirectSignature":{"name":"IncorrectCallIndirectSignature","subtypes":[],"props":{}},"Instantiate":{"name":"Instantiate","subtypes":[],"props":{}},"IntegerOverflow":{"name":"IntegerOverflow","subtypes":[],"props":{}},"InternalMemoryDeclared":{"name":"InternalMemoryDeclared","subtypes":[],"props":{}},"InvalidAccountId":{"name":"InvalidAccountId","subtypes":[],"props":{"account_id":""}},"InvalidIteratorIndex":{"name":"InvalidIteratorIndex","subtypes":[],"props":{"iterator_index":""}},"InvalidMethodName":{"name":"InvalidMethodName","subtypes":[],"props":{}},"InvalidPromiseIndex":{"name":"InvalidPromiseIndex","subtypes":[],"props":{"promise_idx":""}},"InvalidPromiseResultIndex":{"name":"InvalidPromiseResultIndex","subtypes":[],"props":{"result_idx":""}},"InvalidPublicKey":{"name":"InvalidPublicKey","subtypes":[],"props":{}},"InvalidReceiptIndex":{"name":"InvalidReceiptIndex","subtypes":[],"props":{"receipt_index":""}},"InvalidRegisterId":{"name":"InvalidRegisterId","subtypes":[],"props":{"register_id":""}},"IteratorWasInvalidated":{"name":"IteratorWasInvalidated","subtypes":[],"props":{"iterator_index":""}},"KeyLengthExceeded":{"name":"KeyLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"LinkError":{"name":"LinkError","subtypes":[],"props":{"msg":""}},"Memory":{"name":"Memory","subtypes":[],"props":{}},"MemoryAccessViolation":{"name":"MemoryAccessViolation","subtypes":[],"props":{}},"MemoryOutOfBounds":{"name":"MemoryOutOfBounds","subtypes":[],"props":{}},"MethodEmptyName":{"name":"MethodEmptyName","subtypes":[],"props":{}},"MethodInvalidSignature":{"name":"MethodInvalidSignature","subtypes":[],"props":{}},"MethodNotFound":{"name":"MethodNotFound","subtypes":[],"props":{}},"MethodResolveError":{"name":"MethodResolveError","subtypes":["MethodEmptyName","MethodUTF8Error","MethodNotFound","MethodInvalidSignature"],"props":{}},"MethodUTF8Error":{"name":"MethodUTF8Error","subtypes":[],"props":{}},"MisalignedAtomicAccess":{"name":"MisalignedAtomicAccess","subtypes":[],"props":{}},"NumberInputDataDependenciesExceeded":{"name":"NumberInputDataDependenciesExceeded","subtypes":[],"props":{"limit":"","number_of_input_data_dependencies":""}},"NumberOfLogsExceeded":{"name":"NumberOfLogsExceeded","subtypes":[],"props":{"limit":""}},"NumberPromisesExceeded":{"name":"NumberPromisesExceeded","subtypes":[],"props":{"limit":"","number_of_promises":""}},"PrepareError":{"name":"PrepareError","subtypes":["Serialization","Deserialization","InternalMemoryDeclared","GasInstrumentation","StackHeightInstrumentation","Instantiate","Memory"],"props":{}},"ProhibitedInView":{"name":"ProhibitedInView","subtypes":[],"props":{"method_name":""}},"ReadError":{"name":"ReadError","subtypes":[],"props":{}},"ReturnedValueLengthExceeded":{"name":"ReturnedValueLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"Serialization":{"name":"Serialization","subtypes":[],"props":{}},"SerializationError":{"name":"SerializationError","subtypes":[],"props":{"hash":""}},"StackHeightInstrumentation":{"name":"StackHeightInstrumentation","subtypes":[],"props":{}},"StackOverflow":{"name":"StackOverflow","subtypes":[],"props":{}},"TotalLogLengthExceeded":{"name":"TotalLogLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"Unreachable":{"name":"Unreachable","subtypes":[],"props":{}},"ValueLengthExceeded":{"name":"ValueLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"WasmTrap":{"name":"WasmTrap","subtypes":["Unreachable","IncorrectCallIndirectSignature","MemoryOutOfBounds","CallIndirectOOB","IllegalArithmetic","MisalignedAtomicAccess","BreakpointTrap","StackOverflow","GenericTrap"],"props":{}},"WasmUnknownError":{"name":"WasmUnknownError","subtypes":[],"props":{}},"WasmerCompileError":{"name":"WasmerCompileError","subtypes":[],"props":{"msg":""}},"WriteError":{"name":"WriteError","subtypes":[],"props":{}},"AccessKeyNotFound":{"name":"AccessKeyNotFound","subtypes":[],"props":{"account_id":"","public_key":""}},"AccountAlreadyExists":{"name":"AccountAlreadyExists","subtypes":[],"props":{"account_id":""}},"AccountDoesNotExist":{"name":"AccountDoesNotExist","subtypes":[],"props":{"account_id":""}},"ActionError":{"name":"ActionError","subtypes":["AccountAlreadyExists","AccountDoesNotExist","CreateAccountOnlyByRegistrar","CreateAccountNotAllowed","ActorNoPermission","DeleteKeyDoesNotExist","AddKeyAlreadyExists","DeleteAccountStaking","LackBalanceForState","TriesToUnstake","TriesToStake","InsufficientStake","FunctionCallError","NewReceiptValidationError","OnlyImplicitAccountCreationAllowed"],"props":{"index":""}},"ActionsValidationError":{"name":"ActionsValidationError","subtypes":["DeleteActionMustBeFinal","TotalPrepaidGasExceeded","TotalNumberOfActionsExceeded","AddKeyMethodNamesNumberOfBytesExceeded","AddKeyMethodNameLengthExceeded","IntegerOverflow","InvalidAccountId","ContractSizeExceeded","FunctionCallMethodNameLengthExceeded","FunctionCallArgumentsLengthExceeded","UnsuitableStakingKey","FunctionCallZeroAttachedGas"],"props":{}},"ActorNoPermission":{"name":"ActorNoPermission","subtypes":[],"props":{"account_id":"","actor_id":""}},"AddKeyAlreadyExists":{"name":"AddKeyAlreadyExists","subtypes":[],"props":{"account_id":"","public_key":""}},"AddKeyMethodNameLengthExceeded":{"name":"AddKeyMethodNameLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"AddKeyMethodNamesNumberOfBytesExceeded":{"name":"AddKeyMethodNamesNumberOfBytesExceeded","subtypes":[],"props":{"limit":"","total_number_of_bytes":""}},"BalanceMismatchError":{"name":"BalanceMismatchError","subtypes":[],"props":{"final_accounts_balance":"","final_postponed_receipts_balance":"","incoming_receipts_balance":"","incoming_validator_rewards":"","initial_accounts_balance":"","initial_postponed_receipts_balance":"","new_delayed_receipts_balance":"","other_burnt_amount":"","outgoing_receipts_balance":"","processed_delayed_receipts_balance":"","slashed_burnt_amount":"","tx_burnt_amount":""}},"CostOverflow":{"name":"CostOverflow","subtypes":[],"props":{}},"CreateAccountNotAllowed":{"name":"CreateAccountNotAllowed","subtypes":[],"props":{"account_id":"","predecessor_id":""}},"CreateAccountOnlyByRegistrar":{"name":"CreateAccountOnlyByRegistrar","subtypes":[],"props":{"account_id":"","predecessor_id":"","registrar_account_id":""}},"DeleteAccountStaking":{"name":"DeleteAccountStaking","subtypes":[],"props":{"account_id":""}},"DeleteActionMustBeFinal":{"name":"DeleteActionMustBeFinal","subtypes":[],"props":{}},"DeleteKeyDoesNotExist":{"name":"DeleteKeyDoesNotExist","subtypes":[],"props":{"account_id":"","public_key":""}},"DepositWithFunctionCall":{"name":"DepositWithFunctionCall","subtypes":[],"props":{}},"Expired":{"name":"Expired","subtypes":[],"props":{}},"FunctionCallArgumentsLengthExceeded":{"name":"FunctionCallArgumentsLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"FunctionCallMethodNameLengthExceeded":{"name":"FunctionCallMethodNameLengthExceeded","subtypes":[],"props":{"length":"","limit":""}},"FunctionCallZeroAttachedGas":{"name":"FunctionCallZeroAttachedGas","subtypes":[],"props":{}},"InsufficientStake":{"name":"InsufficientStake","subtypes":[],"props":{"account_id":"","minimum_stake":"","stake":""}},"InvalidAccessKeyError":{"name":"InvalidAccessKeyError","subtypes":["AccessKeyNotFound","ReceiverMismatch","MethodNameMismatch","RequiresFullAccess","NotEnoughAllowance","DepositWithFunctionCall"],"props":{}},"InvalidChain":{"name":"InvalidChain","subtypes":[],"props":{}},"InvalidDataReceiverId":{"name":"InvalidDataReceiverId","subtypes":[],"props":{"account_id":""}},"InvalidNonce":{"name":"InvalidNonce","subtypes":[],"props":{"ak_nonce":"","tx_nonce":""}},"InvalidPredecessorId":{"name":"InvalidPredecessorId","subtypes":[],"props":{"account_id":""}},"InvalidReceiverId":{"name":"InvalidReceiverId","subtypes":[],"props":{"account_id":""}},"InvalidSignature":{"name":"InvalidSignature","subtypes":[],"props":{}},"InvalidSignerId":{"name":"InvalidSignerId","subtypes":[],"props":{"account_id":""}},"InvalidTxError":{"name":"InvalidTxError","subtypes":["InvalidAccessKeyError","InvalidSignerId","SignerDoesNotExist","InvalidNonce","InvalidReceiverId","InvalidSignature","NotEnoughBalance","LackBalanceForState","CostOverflow","InvalidChain","Expired","ActionsValidation"],"props":{}},"LackBalanceForState":{"name":"LackBalanceForState","subtypes":[],"props":{"account_id":"","amount":""}},"MethodNameMismatch":{"name":"MethodNameMismatch","subtypes":[],"props":{"method_name":""}},"NotEnoughAllowance":{"name":"NotEnoughAllowance","subtypes":[],"props":{"account_id":"","allowance":"","cost":"","public_key":""}},"NotEnoughBalance":{"name":"NotEnoughBalance","subtypes":[],"props":{"balance":"","cost":"","signer_id":""}},"OnlyImplicitAccountCreationAllowed":{"name":"OnlyImplicitAccountCreationAllowed","subtypes":[],"props":{"account_id":""}},"ReceiptValidationError":{"name":"ReceiptValidationError","subtypes":["InvalidPredecessorId","InvalidReceiverId","InvalidSignerId","InvalidDataReceiverId","ReturnedValueLengthExceeded","NumberInputDataDependenciesExceeded","ActionsValidation"],"props":{}},"ReceiverMismatch":{"name":"ReceiverMismatch","subtypes":[],"props":{"ak_receiver":"","tx_receiver":""}},"RequiresFullAccess":{"name":"RequiresFullAccess","subtypes":[],"props":{}},"SignerDoesNotExist":{"name":"SignerDoesNotExist","subtypes":[],"props":{"signer_id":""}},"TotalNumberOfActionsExceeded":{"name":"TotalNumberOfActionsExceeded","subtypes":[],"props":{"limit":"","total_number_of_actions":""}},"TotalPrepaidGasExceeded":{"name":"TotalPrepaidGasExceeded","subtypes":[],"props":{"limit":"","total_prepaid_gas":""}},"TriesToStake":{"name":"TriesToStake","subtypes":[],"props":{"account_id":"","balance":"","locked":"","stake":""}},"TriesToUnstake":{"name":"TriesToUnstake","subtypes":[],"props":{"account_id":""}},"TxExecutionError":{"name":"TxExecutionError","subtypes":["ActionError","InvalidTxError"],"props":{}},"UnsuitableStakingKey":{"name":"UnsuitableStakingKey","subtypes":[],"props":{"public_key":""}},"Closed":{"name":"Closed","subtypes":[],"props":{}},"InternalError":{"name":"InternalError","subtypes":[],"props":{}},"ServerError":{"name":"ServerError","subtypes":["TxExecutionError","Timeout","Closed","InternalError"],"props":{}},"Timeout":{"name":"Timeout","subtypes":[],"props":{}}}}');
},{}],"1Z5Hy":[function(require,module,exports) {
module.exports = JSON.parse('{"GasLimitExceeded":"Exceeded the maximum amount of gas allowed to burn per contract","MethodEmptyName":"Method name is empty","WasmerCompileError":"Wasmer compilation error: {{msg}}","GuestPanic":"Smart contract panicked: {{panic_msg}}","Memory":"Error creating Wasm memory","GasExceeded":"Exceeded the prepaid gas","MethodUTF8Error":"Method name is not valid UTF8 string","BadUTF16":"String encoding is bad UTF-16 sequence","WasmTrap":"WebAssembly trap: {{msg}}","GasInstrumentation":"Gas instrumentation failed or contract has denied instructions.","InvalidPromiseIndex":"{{promise_idx}} does not correspond to existing promises","InvalidPromiseResultIndex":"Accessed invalid promise result index: {{result_idx}}","Deserialization":"Error happened while deserializing the module","MethodNotFound":"Contract method is not found","InvalidRegisterId":"Accessed invalid register id: {{register_id}}","InvalidReceiptIndex":"VM Logic returned an invalid receipt index: {{receipt_index}}","EmptyMethodName":"Method name is empty in contract call","CannotReturnJointPromise":"Returning joint promise is currently prohibited","StackHeightInstrumentation":"Stack instrumentation failed","CodeDoesNotExist":"Cannot find contract code for account {{account_id}}","MethodInvalidSignature":"Invalid method signature","IntegerOverflow":"Integer overflow happened during contract execution","MemoryAccessViolation":"MemoryAccessViolation","InvalidIteratorIndex":"Iterator index {{iterator_index}} does not exist","IteratorWasInvalidated":"Iterator {{iterator_index}} was invalidated after its creation by performing a mutable operation on trie","InvalidAccountId":"VM Logic returned an invalid account id","Serialization":"Error happened while serializing the module","CannotAppendActionToJointPromise":"Actions can only be appended to non-joint promise.","InternalMemoryDeclared":"Internal memory declaration has been found in the module","Instantiate":"Error happened during instantiation","ProhibitedInView":"{{method_name}} is not allowed in view calls","InvalidMethodName":"VM Logic returned an invalid method name","BadUTF8":"String encoding is bad UTF-8 sequence","BalanceExceeded":"Exceeded the account balance","LinkError":"Wasm contract link error: {{msg}}","InvalidPublicKey":"VM Logic provided an invalid public key","ActorNoPermission":"Actor {{actor_id}} doesn\'t have permission to account {{account_id}} to complete the action","LackBalanceForState":"The account {{account_id}} wouldn\'t have enough balance to cover storage, required to have {{amount}} yoctoNEAR more","ReceiverMismatch":"Wrong AccessKey used for transaction: transaction is sent to receiver_id={{tx_receiver}}, but is signed with function call access key that restricted to only use with receiver_id={{ak_receiver}}. Either change receiver_id in your transaction or switch to use a FullAccessKey.","CostOverflow":"Transaction gas or balance cost is too high","InvalidSignature":"Transaction is not signed with the given public key","AccessKeyNotFound":"Signer \\"{{account_id}}\\" doesn\'t have access key with the given public_key {{public_key}}","NotEnoughBalance":"Sender {{signer_id}} does not have enough balance {{#formatNear}}{{balance}}{{/formatNear}} for operation costing {{#formatNear}}{{cost}}{{/formatNear}}","NotEnoughAllowance":"Access Key {account_id}:{public_key} does not have enough balance {{#formatNear}}{{allowance}}{{/formatNear}} for transaction costing {{#formatNear}}{{cost}}{{/formatNear}}","Expired":"Transaction has expired","DeleteAccountStaking":"Account {{account_id}} is staking and can not be deleted","SignerDoesNotExist":"Signer {{signer_id}} does not exist","TriesToStake":"Account {{account_id}} tried to stake {{#formatNear}}{{stake}}{{/formatNear}}, but has staked {{#formatNear}}{{locked}}{{/formatNear}} and only has {{#formatNear}}{{balance}}{{/formatNear}}","AddKeyAlreadyExists":"The public key {{public_key}} is already used for an existing access key","InvalidSigner":"Invalid signer account ID {{signer_id}} according to requirements","CreateAccountNotAllowed":"The new account_id {{account_id}} can\'t be created by {{predecessor_id}}","RequiresFullAccess":"The transaction contains more then one action, but it was signed with an access key which allows transaction to apply only one specific action. To apply more then one actions TX must be signed with a full access key","TriesToUnstake":"Account {{account_id}} is not yet staked, but tried to unstake","InvalidNonce":"Transaction nonce {{tx_nonce}} must be larger than nonce of the used access key {{ak_nonce}}","AccountAlreadyExists":"Can\'t create a new account {{account_id}}, because it already exists","InvalidChain":"Transaction parent block hash doesn\'t belong to the current chain","AccountDoesNotExist":"Can\'t complete the action because account {{account_id}} doesn\'t exist","MethodNameMismatch":"Transaction method name {{method_name}} isn\'t allowed by the access key","DeleteAccountHasRent":"Account {{account_id}} can\'t be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover the rent","DeleteAccountHasEnoughBalance":"Account {{account_id}} can\'t be deleted. It has {{#formatNear}}{{balance}}{{/formatNear}}, which is enough to cover it\'s storage","InvalidReceiver":"Invalid receiver account ID {{receiver_id}} according to requirements","DeleteKeyDoesNotExist":"Account {{account_id}} tries to remove an access key that doesn\'t exist","Timeout":"Timeout exceeded","Closed":"Connection closed"}');
},{}],"jOCMH":[function(require,module,exports) {
"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: function() {
return m[k];
}
});
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.logWarning = exports.rpc_errors = exports.KeyPairEd25519 = exports.KeyPair = exports.PublicKey = exports.format = exports.enums = exports.web = exports.serialize = exports.key_pair = void 0;
const key_pair = __importStar(require("./key_pair"));
exports.key_pair = key_pair;
const serialize = __importStar(require("./serialize"));
exports.serialize = serialize;
const web = __importStar(require("./web"));
exports.web = web;
const enums = __importStar(require("./enums"));
exports.enums = enums;
const format = __importStar(require("./format"));
exports.format = format;
const rpc_errors = __importStar(require("./rpc_errors"));
exports.rpc_errors = rpc_errors;
const key_pair_1 = require("./key_pair");
Object.defineProperty(exports, "PublicKey", {
enumerable: true,
get: function() {
return key_pair_1.PublicKey;
}
});
Object.defineProperty(exports, "KeyPair", {
enumerable: true,
get: function() {
return key_pair_1.KeyPair;
}
});
Object.defineProperty(exports, "KeyPairEd25519", {
enumerable: true,
get: function() {
return key_pair_1.KeyPairEd25519;
}
});
const errors_1 = require("./errors");
Object.defineProperty(exports, "logWarning", {
enumerable: true,
get: function() {
return errors_1.logWarning;
}
});
},{"./key_pair":"kBQFP","./serialize":"dUoM9","./web":"iSqiB","./enums":"kjmPo","./format":"16c5X","./rpc_errors":"1TB1L","./errors":"btMYy"}],"16c5X":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseNearAmount = exports.formatNearAmount = exports.NEAR_NOMINATION = exports.NEAR_NOMINATION_EXP = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
/**
* Exponent for calculating how many indivisible units are there in one NEAR. See {@link NEAR_NOMINATION}.
*/ exports.NEAR_NOMINATION_EXP = 24;
/**
* Number of indivisible units in one NEAR. Derived from {@link NEAR_NOMINATION_EXP}.
*/ exports.NEAR_NOMINATION = new bn_js_1.default("10", 10).pow(new bn_js_1.default(exports.NEAR_NOMINATION_EXP, 10));
// Pre-calculate offests used for rounding to different number of digits
const ROUNDING_OFFSETS = [];
const BN10 = new bn_js_1.default(10);
for(let i = 0, offset = new bn_js_1.default(5); i < exports.NEAR_NOMINATION_EXP; i++, offset = offset.mul(BN10))ROUNDING_OFFSETS[i] = offset;
/**
* Convert account balance value from internal indivisible units to NEAR. 1 NEAR is defined by {@link NEAR_NOMINATION}.
* Effectively this divides given amount by {@link NEAR_NOMINATION}.
*
* @param balance decimal string representing balance in smallest non-divisible NEAR units (as specified by {@link NEAR_NOMINATION})
* @param fracDigits number of fractional digits to preserve in formatted string. Balance is rounded to match given number of digits.
* @returns Value in Ⓝ
*/ function formatNearAmount(balance, fracDigits = exports.NEAR_NOMINATION_EXP) {
const balanceBN = new bn_js_1.default(balance, 10);
if (fracDigits !== exports.NEAR_NOMINATION_EXP) {
// Adjust balance for rounding at given number of digits
const roundingExp = exports.NEAR_NOMINATION_EXP - fracDigits - 1;
if (roundingExp > 0) balanceBN.iadd(ROUNDING_OFFSETS[roundingExp]);
}
balance = balanceBN.toString();
const wholeStr = balance.substring(0, balance.length - exports.NEAR_NOMINATION_EXP) || "0";
const fractionStr = balance.substring(balance.length - exports.NEAR_NOMINATION_EXP).padStart(exports.NEAR_NOMINATION_EXP, "0").substring(0, fracDigits);
return trimTrailingZeroes(`${formatWithCommas(wholeStr)}.${fractionStr}`);
}
exports.formatNearAmount = formatNearAmount;
/**
* Convert human readable NEAR amount to internal indivisible units.
* Effectively this multiplies given amount by {@link NEAR_NOMINATION}.
*
* @param amt decimal string (potentially fractional) denominated in NEAR.
* @returns The parsed yoctoⓃ amount or null if no amount was passed in
*/ function parseNearAmount(amt) {
if (!amt) return null;
amt = cleanupAmount(amt);
const split = amt.split(".");
const wholePart = split[0];
const fracPart = split[1] || "";
if (split.length > 2 || fracPart.length > exports.NEAR_NOMINATION_EXP) throw new Error(`Cannot parse '${amt}' as NEAR amount`);
return trimLeadingZeroes(wholePart + fracPart.padEnd(exports.NEAR_NOMINATION_EXP, "0"));
}
exports.parseNearAmount = parseNearAmount;
/**
* Removes commas from the input
* @param amount A value or amount that may contain commas
* @returns string The cleaned value
*/ function cleanupAmount(amount) {
return amount.replace(/,/g, "").trim();
}
/**
* Removes .000… from an input
* @param value A value that may contain trailing zeroes in the decimals place
* @returns string The value without the trailing zeros
*/ function trimTrailingZeroes(value) {
return value.replace(/\.?0*$/, "");
}
/**
* Removes leading zeroes from an input
* @param value A value that may contain leading zeroes
* @returns string The value without the leading zeroes
*/ function trimLeadingZeroes(value) {
value = value.replace(/^0+/, "");
if (value === "") return "0";
return value;
}
/**
* Returns a human-readable value with commas
* @param value A value that may not contain commas
* @returns string A value with commas
*/ function formatWithCommas(value) {
const pattern = /(-?\d+)(\d{3})/;
while(pattern.test(value))value = value.replace(pattern, "$1,$2");
return value;
}
},{"bn.js":"9pdNn"}],"9pdNn":[function(require,module,exports) {
(function(module1, exports) {
"use strict";
// Utils
function assert(val, msg) {
if (!val) throw new Error(msg || "Assertion failed");
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function() {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN(number, base, endian) {
if (BN.isBN(number)) return number;
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === "le" || base === "be") {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || "be");
}
}
if (typeof module1 === "object") module1.exports = BN;
else exports.BN = BN;
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") Buffer = window.Buffer;
else Buffer = require("buffer").Buffer;
} catch (e) {}
BN.isBN = function isBN(num) {
if (num instanceof BN) return true;
return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max(left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min(left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init(number, base, endian) {
if (typeof number === "number") return this._initNumber(number, base, endian);
if (typeof number === "object") return this._initArray(number, base, endian);
if (base === "hex") base = 16;
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, "");
var start = 0;
if (number[0] === "-") {
start++;
this.negative = 1;
}
if (start < number.length) {
if (base === 16) this._parseHex(number, start, endian);
else {
this._parseBase(number, base, start);
if (endian === "le") this._initArray(this.toArray(), base, endian);
}
}
};
BN.prototype._initNumber = function _initNumber(number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [
number & 0x3ffffff
];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
number / 0x4000000 & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
number / 0x4000000 & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== "le") return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray(number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === "number");
if (number.length <= 0) {
this.words = [
0
];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for(var i = 0; i < this.length; i++)this.words[i] = 0;
var j, w;
var off = 0;
if (endian === "be") for(i = number.length - 1, j = 0; i >= 0; i -= 3){
w = number[i] | number[i - 1] << 8 | number[i - 2] << 16;
this.words[j] |= w << off & 0x3ffffff;
this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
else if (endian === "le") for(i = 0, j = 0; i < number.length; i += 3){
w = number[i] | number[i + 1] << 8 | number[i + 2] << 16;
this.words[j] |= w << off & 0x3ffffff;
this.words[j + 1] = w >>> 26 - off & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
return this._strip();
};
function parseHex4Bits(string, index) {
var c = string.charCodeAt(index);
// '0' - '9'
if (c >= 48 && c <= 57) return c - 48;
else if (c >= 65 && c <= 70) return c - 55;
else if (c >= 97 && c <= 102) return c - 87;
else assert(false, "Invalid character in " + string);
}
function parseHexByte(string, lowerBound, index) {
var r = parseHex4Bits(string, index);
if (index - 1 >= lowerBound) r |= parseHex4Bits(string, index - 1) << 4;
return r;
}
BN.prototype._parseHex = function _parseHex(number, start, endian) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for(var i = 0; i < this.length; i++)this.words[i] = 0;
// 24-bits chunks
var off = 0;
var j = 0;
var w;
if (endian === "be") for(i = number.length - 1; i >= start; i -= 2){
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else off += 8;
}
else {
var parseLength = number.length - start;
for(i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2){
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else off += 8;
}
}
this._strip();
};
function parseBase(str, start, end, mul) {
var r = 0;
var b = 0;
var len = Math.min(str.length, end);
for(var i = start; i < len; i++){
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) b = c - 49 + 0xa;
else if (c >= 17) b = c - 17 + 0xa;
else b = c;
assert(c >= 0 && b < mul, "Invalid character");
r += b;
}
return r;
}
BN.prototype._parseBase = function _parseBase(number, base, start) {
// Initialize as zero
this.words = [
0
];
this.length = 1;
// Find length of limb in base
for(var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)limbLen++;
limbLen--;
limbPow = limbPow / base | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for(var i = start; i < end; i += limbLen){
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) this.words[0] += word;
else this._iaddn(word);
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for(i = 0; i < mod; i++)pow *= base;
this.imuln(pow);
if (this.words[0] + word < 0x4000000) this.words[0] += word;
else this._iaddn(word);
}
this._strip();
};
BN.prototype.copy = function copy(dest) {
dest.words = new Array(this.length);
for(var i = 0; i < this.length; i++)dest.words[i] = this.words[i];
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
function move(dest, src) {
dest.words = src.words;
dest.length = src.length;
dest.negative = src.negative;
dest.red = src.red;
}
BN.prototype._move = function _move(dest) {
move(dest, this);
};
BN.prototype.clone = function clone() {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand(size) {
while(this.length < size)this.words[this.length++] = 0;
return this;
};
// Remove leading `0` from `this`
BN.prototype._strip = function strip() {
while(this.length > 1 && this.words[this.length - 1] === 0)this.length--;
return this._normSign();
};
BN.prototype._normSign = function _normSign() {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) this.negative = 0;
return this;
};
// Check Symbol.for because not everywhere where Symbol defined
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") try {
BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect;
} catch (e1) {
BN.prototype.inspect = inspect;
}
else BN.prototype.inspect = inspect;
function inspect() {
return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
}
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/ var zeros = [
"",
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
"00000000",
"000000000",
"0000000000",
"00000000000",
"000000000000",
"0000000000000",
"00000000000000",
"000000000000000",
"0000000000000000",
"00000000000000000",
"000000000000000000",
"0000000000000000000",
"00000000000000000000",
"000000000000000000000",
"0000000000000000000000",
"00000000000000000000000",
"000000000000000000000000",
"0000000000000000000000000"
];
var groupSizes = [
0,
0,
25,
16,
12,
11,
10,
9,
8,
8,
7,
7,
7,
7,
6,
6,
6,
6,
6,
6,
6,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5
];
var groupBases = [
0,
0,
33554432,
43046721,
16777216,
48828125,
60466176,
40353607,
16777216,
43046721,
10000000,
19487171,
35831808,
62748517,
7529536,
11390625,
16777216,
24137569,
34012224,
47045881,
64000000,
4084101,
5153632,
6436343,
7962624,
9765625,
11881376,
14348907,
17210368,
20511149,
24300000,
28629151,
33554432,
39135393,
45435424,
52521875,
60466176
];
BN.prototype.toString = function toString(base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === "hex") {
out = "";
var off = 0;
var carry = 0;
for(var i = 0; i < this.length; i++){
var w = this.words[i];
var word = ((w << off | carry) & 0xffffff).toString(16);
carry = w >>> 24 - off & 0xffffff;
if (carry !== 0 || i !== this.length - 1) out = zeros[6 - word.length] + word + out;
else out = word + out;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
}
if (carry !== 0) out = carry.toString(16) + out;
while(out.length % padding !== 0)out = "0" + out;
if (this.negative !== 0) out = "-" + out;
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = "";
var c = this.clone();
c.negative = 0;
while(!c.isZero()){
var r = c.modrn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) out = zeros[groupSize - r.length] + r + out;
else out = r + out;
}
if (this.isZero()) out = "0" + out;
while(out.length % padding !== 0)out = "0" + out;
if (this.negative !== 0) out = "-" + out;
return out;
}
assert(false, "Base should be between 2 and 36");
};
BN.prototype.toNumber = function toNumber() {
var ret = this.words[0];
if (this.length === 2) ret += this.words[1] * 0x4000000;
else if (this.length === 3 && this.words[2] === 0x01) // NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + this.words[1] * 0x4000000;
else if (this.length > 2) assert(false, "Number can only safely store up to 53 bits");
return this.negative !== 0 ? -ret : ret;
};
BN.prototype.toJSON = function toJSON() {
return this.toString(16, 2);
};
if (Buffer) BN.prototype.toBuffer = function toBuffer(endian, length) {
return this.toArrayLike(Buffer, endian, length);
};
BN.prototype.toArray = function toArray(endian, length) {
return this.toArrayLike(Array, endian, length);
};
var allocate = function allocate(ArrayType, size) {
if (ArrayType.allocUnsafe) return ArrayType.allocUnsafe(size);
return new ArrayType(size);
};
BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
this._strip();
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, "byte array longer than desired length");
assert(reqLength > 0, "Requested array length <= 0");
var res = allocate(ArrayType, reqLength);
var postfix = endian === "le" ? "LE" : "BE";
this["_toArrayLike" + postfix](res, byteLength);
return res;
};
BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) {
var position = 0;
var carry = 0;
for(var i = 0, shift = 0; i < this.length; i++){
var word = this.words[i] << shift | carry;
res[position++] = word & 0xff;
if (position < res.length) res[position++] = word >> 8 & 0xff;
if (position < res.length) res[position++] = word >> 16 & 0xff;
if (shift === 6) {
if (position < res.length) res[position++] = word >> 24 & 0xff;
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position < res.length) {
res[position++] = carry;
while(position < res.length)res[position++] = 0;
}
};
BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) {
var position = res.length - 1;
var carry = 0;
for(var i = 0, shift = 0; i < this.length; i++){
var word = this.words[i] << shift | carry;
res[position--] = word & 0xff;
if (position >= 0) res[position--] = word >> 8 & 0xff;
if (position >= 0) res[position--] = word >> 16 & 0xff;
if (shift === 6) {
if (position >= 0) res[position--] = word >> 24 & 0xff;
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position >= 0) {
res[position--] = carry;
while(position >= 0)res[position--] = 0;
}
};
if (Math.clz32) BN.prototype._countBits = function _countBits(w) {
return 32 - Math.clz32(w);
};
else BN.prototype._countBits = function _countBits(w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
BN.prototype._zeroBits = function _zeroBits(w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) r++;
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength() {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray(num) {
var w = new Array(num.bitLength());
for(var bit = 0; bit < w.length; bit++){
var off = bit / 26 | 0;
var wbit = bit % 26;
w[bit] = num.words[off] >>> wbit & 0x01;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits() {
if (this.isZero()) return 0;
var r = 0;
for(var i = 0; i < this.length; i++){
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength() {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos(width) {
if (this.negative !== 0) return this.abs().inotn(width).iaddn(1);
return this.clone();
};
BN.prototype.fromTwos = function fromTwos(width) {
if (this.testn(width - 1)) return this.notn(width).iaddn(1).ineg();
return this.clone();
};
BN.prototype.isNeg = function isNeg() {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg() {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg() {
if (!this.isZero()) this.negative ^= 1;
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor(num) {
while(this.length < num.length)this.words[this.length++] = 0;
for(var i = 0; i < num.length; i++)this.words[i] = this.words[i] | num.words[i];
return this._strip();
};
BN.prototype.ior = function ior(num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or(num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor(num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand(num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) b = num;
else b = this;
for(var i = 0; i < b.length; i++)this.words[i] = this.words[i] & num.words[i];
this.length = b.length;
return this._strip();
};
BN.prototype.iand = function iand(num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and(num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand(num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor(num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for(var i = 0; i < b.length; i++)this.words[i] = a.words[i] ^ b.words[i];
if (this !== a) for(; i < a.length; i++)this.words[i] = a.words[i];
this.length = a.length;
return this._strip();
};
BN.prototype.ixor = function ixor(num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor(num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor(num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn(width) {
assert(typeof width === "number" && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) bytesNeeded--;
// Handle complete words
for(var i = 0; i < bytesNeeded; i++)this.words[i] = ~this.words[i] & 0x3ffffff;
// Handle the residue
if (bitsLeft > 0) this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft;
// And remove leading zeroes
return this._strip();
};
BN.prototype.notn = function notn(width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn(bit, val) {
assert(typeof bit === "number" && bit >= 0);
var off = bit / 26 | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) this.words[off] = this.words[off] | 1 << wbit;
else this.words[off] = this.words[off] & ~(1 << wbit);
return this._strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd(num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for(var i = 0; i < b.length; i++){
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for(; carry !== 0 && i < a.length; i++){
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) for(; i < a.length; i++)this.words[i] = a.words[i];
return this;
};
// Add `num` to `this`
BN.prototype.add = function add(num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub(num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for(var i = 0; i < b.length; i++){
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for(; carry !== 0 && i < a.length; i++){
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) for(; i < a.length; i++)this.words[i] = a.words[i];
this.length = Math.max(this.length, i);
if (a !== this) this.negative = 1;
return this._strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub(num) {
return this.clone().isub(num);
};
function smallMulTo(self, num, out) {
out.negative = num.negative ^ self.negative;
var len = self.length + num.length | 0;
out.length = len;
len = len - 1 | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = r / 0x4000000 | 0;
out.words[0] = lo;
for(var k = 1; k < len; k++){
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for(var j = Math.max(0, k - self.length + 1); j <= maxJ; j++){
var i = k - j | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += r / 0x4000000 | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) out.words[k] = carry | 0;
else out.length--;
return out._strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo(self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */ lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = mid + Math.imul(ah0, bl0) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
w0 &= 0x3ffffff;
/* k = 1 */ lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = mid + Math.imul(ah1, bl0) | 0;
hi = Math.imul(ah1, bh0);
lo = lo + Math.imul(al0, bl1) | 0;
mid = mid + Math.imul(al0, bh1) | 0;
mid = mid + Math.imul(ah0, bl1) | 0;
hi = hi + Math.imul(ah0, bh1) | 0;
var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
w1 &= 0x3ffffff;
/* k = 2 */ lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = mid + Math.imul(ah2, bl0) | 0;
hi = Math.imul(ah2, bh0);
lo = lo + Math.imul(al1, bl1) | 0;
mid = mid + Math.imul(al1, bh1) | 0;
mid = mid + Math.imul(ah1, bl1) | 0;
hi = hi + Math.imul(ah1, bh1) | 0;
lo = lo + Math.imul(al0, bl2) | 0;
mid = mid + Math.imul(al0, bh2) | 0;
mid = mid + Math.imul(ah0, bl2) | 0;
hi = hi + Math.imul(ah0, bh2) | 0;
var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
w2 &= 0x3ffffff;
/* k = 3 */ lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = mid + Math.imul(ah3, bl0) | 0;
hi = Math.imul(ah3, bh0);
lo = lo + Math.imul(al2, bl1) | 0;
mid = mid + Math.imul(al2, bh1) | 0;
mid = mid + Math.imul(ah2, bl1) | 0;
hi = hi + Math.imul(ah2, bh1) | 0;
lo = lo + Math.imul(al1, bl2) | 0;
mid = mid + Math.imul(al1, bh2) | 0;
mid = mid + Math.imul(ah1, bl2) | 0;
hi = hi + Math.imul(ah1, bh2) | 0;
lo = lo + Math.imul(al0, bl3) | 0;
mid = mid + Math.imul(al0, bh3) | 0;
mid = mid + Math.imul(ah0, bl3) | 0;
hi = hi + Math.imul(ah0, bh3) | 0;
var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
w3 &= 0x3ffffff;
/* k = 4 */ lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = mid + Math.imul(ah4, bl0) | 0;
hi = Math.imul(ah4, bh0);
lo = lo + Math.imul(al3, bl1) | 0;
mid = mid + Math.imul(al3, bh1) | 0;
mid = mid + Math.imul(ah3, bl1) | 0;
hi = hi + Math.imul(ah3, bh1) | 0;
lo = lo + Math.imul(al2, bl2) | 0;
mid = mid + Math.imul(al2, bh2) | 0;
mid = mid + Math.imul(ah2, bl2) | 0;
hi = hi + Math.imul(ah2, bh2) | 0;
lo = lo + Math.imul(al1, bl3) | 0;
mid = mid + Math.imul(al1, bh3) | 0;
mid = mid + Math.imul(ah1, bl3) | 0;
hi = hi + Math.imul(ah1, bh3) | 0;
lo = lo + Math.imul(al0, bl4) | 0;
mid = mid + Math.imul(al0, bh4) | 0;
mid = mid + Math.imul(ah0, bl4) | 0;
hi = hi + Math.imul(ah0, bh4) | 0;
var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
w4 &= 0x3ffffff;
/* k = 5 */ lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = mid + Math.imul(ah5, bl0) | 0;
hi = Math.imul(ah5, bh0);
lo = lo + Math.imul(al4, bl1) | 0;
mid = mid + Math.imul(al4, bh1) | 0;
mid = mid + Math.imul(ah4, bl1) | 0;
hi = hi + Math.imul(ah4, bh1) | 0;
lo = lo + Math.imul(al3, bl2) | 0;
mid = mid + Math.imul(al3, bh2) | 0;
mid = mid + Math.imul(ah3, bl2) | 0;
hi = hi + Math.imul(ah3, bh2) | 0;
lo = lo + Math.imul(al2, bl3) | 0;
mid = mid + Math.imul(al2, bh3) | 0;
mid = mid + Math.imul(ah2, bl3) | 0;
hi = hi + Math.imul(ah2, bh3) | 0;
lo = lo + Math.imul(al1, bl4) | 0;
mid = mid + Math.imul(al1, bh4) | 0;
mid = mid + Math.imul(ah1, bl4) | 0;
hi = hi + Math.imul(ah1, bh4) | 0;
lo = lo + Math.imul(al0, bl5) | 0;
mid = mid + Math.imul(al0, bh5) | 0;
mid = mid + Math.imul(ah0, bl5) | 0;
hi = hi + Math.imul(ah0, bh5) | 0;
var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
w5 &= 0x3ffffff;
/* k = 6 */ lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = mid + Math.imul(ah6, bl0) | 0;
hi = Math.imul(ah6, bh0);
lo = lo + Math.imul(al5, bl1) | 0;
mid = mid + Math.imul(al5, bh1) | 0;
mid = mid + Math.imul(ah5, bl1) | 0;
hi = hi + Math.imul(ah5, bh1) | 0;
lo = lo + Math.imul(al4, bl2) | 0;
mid = mid + Math.imul(al4, bh2) | 0;
mid = mid + Math.imul(ah4, bl2) | 0;
hi = hi + Math.imul(ah4, bh2) | 0;
lo = lo + Math.imul(al3, bl3) | 0;
mid = mid + Math.imul(al3, bh3) | 0;
mid = mid + Math.imul(ah3, bl3) | 0;
hi = hi + Math.imul(ah3, bh3) | 0;
lo = lo + Math.imul(al2, bl4) | 0;
mid = mid + Math.imul(al2, bh4) | 0;
mid = mid + Math.imul(ah2, bl4) | 0;
hi = hi + Math.imul(ah2, bh4) | 0;
lo = lo + Math.imul(al1, bl5) | 0;
mid = mid + Math.imul(al1, bh5) | 0;
mid = mid + Math.imul(ah1, bl5) | 0;
hi = hi + Math.imul(ah1, bh5) | 0;
lo = lo + Math.imul(al0, bl6) | 0;
mid = mid + Math.imul(al0, bh6) | 0;
mid = mid + Math.imul(ah0, bl6) | 0;
hi = hi + Math.imul(ah0, bh6) | 0;
var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
w6 &= 0x3ffffff;
/* k = 7 */ lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = mid + Math.imul(ah7, bl0) | 0;
hi = Math.imul(ah7, bh0);
lo = lo + Math.imul(al6, bl1) | 0;
mid = mid + Math.imul(al6, bh1) | 0;
mid = mid + Math.imul(ah6, bl1) | 0;
hi = hi + Math.imul(ah6, bh1) | 0;
lo = lo + Math.imul(al5, bl2) | 0;
mid = mid + Math.imul(al5, bh2) | 0;
mid = mid + Math.imul(ah5, bl2) | 0;
hi = hi + Math.imul(ah5, bh2) | 0;
lo = lo + Math.imul(al4, bl3) | 0;
mid = mid + Math.imul(al4, bh3) | 0;
mid = mid + Math.imul(ah4, bl3) | 0;
hi = hi + Math.imul(ah4, bh3) | 0;
lo = lo + Math.imul(al3, bl4) | 0;
mid = mid + Math.imul(al3, bh4) | 0;
mid = mid + Math.imul(ah3, bl4) | 0;
hi = hi + Math.imul(ah3, bh4) | 0;
lo = lo + Math.imul(al2, bl5) | 0;
mid = mid + Math.imul(al2, bh5) | 0;
mid = mid + Math.imul(ah2, bl5) | 0;
hi = hi + Math.imul(ah2, bh5) | 0;
lo = lo + Math.imul(al1, bl6) | 0;
mid = mid + Math.imul(al1, bh6) | 0;
mid = mid + Math.imul(ah1, bl6) | 0;
hi = hi + Math.imul(ah1, bh6) | 0;
lo = lo + Math.imul(al0, bl7) | 0;
mid = mid + Math.imul(al0, bh7) | 0;
mid = mid + Math.imul(ah0, bl7) | 0;
hi = hi + Math.imul(ah0, bh7) | 0;
var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
w7 &= 0x3ffffff;
/* k = 8 */ lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = mid + Math.imul(ah8, bl0) | 0;
hi = Math.imul(ah8, bh0);
lo = lo + Math.imul(al7, bl1) | 0;
mid = mid + Math.imul(al7, bh1) | 0;
mid = mid + Math.imul(ah7, bl1) | 0;
hi = hi + Math.imul(ah7, bh1) | 0;
lo = lo + Math.imul(al6, bl2) | 0;
mid = mid + Math.imul(al6, bh2) | 0;
mid = mid + Math.imul(ah6, bl2) | 0;
hi = hi + Math.imul(ah6, bh2) | 0;
lo = lo + Math.imul(al5, bl3) | 0;
mid = mid + Math.imul(al5, bh3) | 0;
mid = mid + Math.imul(ah5, bl3) | 0;
hi = hi + Math.imul(ah5, bh3) | 0;
lo = lo + Math.imul(al4, bl4) | 0;
mid = mid + Math.imul(al4, bh4) | 0;
mid = mid + Math.imul(ah4, bl4) | 0;
hi = hi + Math.imul(ah4, bh4) | 0;
lo = lo + Math.imul(al3, bl5) | 0;
mid = mid + Math.imul(al3, bh5) | 0;
mid = mid + Math.imul(ah3, bl5) | 0;
hi = hi + Math.imul(ah3, bh5) | 0;
lo = lo + Math.imul(al2, bl6) | 0;
mid = mid + Math.imul(al2, bh6) | 0;
mid = mid + Math.imul(ah2, bl6) | 0;
hi = hi + Math.imul(ah2, bh6) | 0;
lo = lo + Math.imul(al1, bl7) | 0;
mid = mid + Math.imul(al1, bh7) | 0;
mid = mid + Math.imul(ah1, bl7) | 0;
hi = hi + Math.imul(ah1, bh7) | 0;
lo = lo + Math.imul(al0, bl8) | 0;
mid = mid + Math.imul(al0, bh8) | 0;
mid = mid + Math.imul(ah0, bl8) | 0;
hi = hi + Math.imul(ah0, bh8) | 0;
var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
w8 &= 0x3ffffff;
/* k = 9 */ lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = mid + Math.imul(ah9, bl0) | 0;
hi = Math.imul(ah9, bh0);
lo = lo + Math.imul(al8, bl1) | 0;
mid = mid + Math.imul(al8, bh1) | 0;
mid = mid + Math.imul(ah8, bl1) | 0;
hi = hi + Math.imul(ah8, bh1) | 0;
lo = lo + Math.imul(al7, bl2) | 0;
mid = mid + Math.imul(al7, bh2) | 0;
mid = mid + Math.imul(ah7, bl2) | 0;
hi = hi + Math.imul(ah7, bh2) | 0;
lo = lo + Math.imul(al6, bl3) | 0;
mid = mid + Math.imul(al6, bh3) | 0;
mid = mid + Math.imul(ah6, bl3) | 0;
hi = hi + Math.imul(ah6, bh3) | 0;
lo = lo + Math.imul(al5, bl4) | 0;
mid = mid + Math.imul(al5, bh4) | 0;
mid = mid + Math.imul(ah5, bl4) | 0;
hi = hi + Math.imul(ah5, bh4) | 0;
lo = lo + Math.imul(al4, bl5) | 0;
mid = mid + Math.imul(al4, bh5) | 0;
mid = mid + Math.imul(ah4, bl5) | 0;
hi = hi + Math.imul(ah4, bh5) | 0;
lo = lo + Math.imul(al3, bl6) | 0;
mid = mid + Math.imul(al3, bh6) | 0;
mid = mid + Math.imul(ah3, bl6) | 0;
hi = hi + Math.imul(ah3, bh6) | 0;
lo = lo + Math.imul(al2, bl7) | 0;
mid = mid + Math.imul(al2, bh7) | 0;
mid = mid + Math.imul(ah2, bl7) | 0;
hi = hi + Math.imul(ah2, bh7) | 0;
lo = lo + Math.imul(al1, bl8) | 0;
mid = mid + Math.imul(al1, bh8) | 0;
mid = mid + Math.imul(ah1, bl8) | 0;
hi = hi + Math.imul(ah1, bh8) | 0;
lo = lo + Math.imul(al0, bl9) | 0;
mid = mid + Math.imul(al0, bh9) | 0;
mid = mid + Math.imul(ah0, bl9) | 0;
hi = hi + Math.imul(ah0, bh9) | 0;
var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
w9 &= 0x3ffffff;
/* k = 10 */ lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = mid + Math.imul(ah9, bl1) | 0;
hi = Math.imul(ah9, bh1);
lo = lo + Math.imul(al8, bl2) | 0;
mid = mid + Math.imul(al8, bh2) | 0;
mid = mid + Math.imul(ah8, bl2) | 0;
hi = hi + Math.imul(ah8, bh2) | 0;
lo = lo + Math.imul(al7, bl3) | 0;
mid = mid + Math.imul(al7, bh3) | 0;
mid = mid + Math.imul(ah7, bl3) | 0;
hi = hi + Math.imul(ah7, bh3) | 0;
lo = lo + Math.imul(al6, bl4) | 0;
mid = mid + Math.imul(al6, bh4) | 0;
mid = mid + Math.imul(ah6, bl4) | 0;
hi = hi + Math.imul(ah6, bh4) | 0;
lo = lo + Math.imul(al5, bl5) | 0;
mid = mid + Math.imul(al5, bh5) | 0;
mid = mid + Math.imul(ah5, bl5) | 0;
hi = hi + Math.imul(ah5, bh5) | 0;
lo = lo + Math.imul(al4, bl6) | 0;
mid = mid + Math.imul(al4, bh6) | 0;
mid = mid + Math.imul(ah4, bl6) | 0;
hi = hi + Math.imul(ah4, bh6) | 0;
lo = lo + Math.imul(al3, bl7) | 0;
mid = mid + Math.imul(al3, bh7) | 0;
mid = mid + Math.imul(ah3, bl7) | 0;
hi = hi + Math.imul(ah3, bh7) | 0;
lo = lo + Math.imul(al2, bl8) | 0;
mid = mid + Math.imul(al2, bh8) | 0;
mid = mid + Math.imul(ah2, bl8) | 0;
hi = hi + Math.imul(ah2, bh8) | 0;
lo = lo + Math.imul(al1, bl9) | 0;
mid = mid + Math.imul(al1, bh9) | 0;
mid = mid + Math.imul(ah1, bl9) | 0;
hi = hi + Math.imul(ah1, bh9) | 0;
var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
w10 &= 0x3ffffff;
/* k = 11 */ lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = mid + Math.imul(ah9, bl2) | 0;
hi = Math.imul(ah9, bh2);
lo = lo + Math.imul(al8, bl3) | 0;
mid = mid + Math.imul(al8, bh3) | 0;
mid = mid + Math.imul(ah8, bl3) | 0;
hi = hi + Math.imul(ah8, bh3) | 0;
lo = lo + Math.imul(al7, bl4) | 0;
mid = mid + Math.imul(al7, bh4) | 0;
mid = mid + Math.imul(ah7, bl4) | 0;
hi = hi + Math.imul(ah7, bh4) | 0;
lo = lo + Math.imul(al6, bl5) | 0;
mid = mid + Math.imul(al6, bh5) | 0;
mid = mid + Math.imul(ah6, bl5) | 0;
hi = hi + Math.imul(ah6, bh5) | 0;
lo = lo + Math.imul(al5, bl6) | 0;
mid = mid + Math.imul(al5, bh6) | 0;
mid = mid + Math.imul(ah5, bl6) | 0;
hi = hi + Math.imul(ah5, bh6) | 0;
lo = lo + Math.imul(al4, bl7) | 0;
mid = mid + Math.imul(al4, bh7) | 0;
mid = mid + Math.imul(ah4, bl7) | 0;
hi = hi + Math.imul(ah4, bh7) | 0;
lo = lo + Math.imul(al3, bl8) | 0;
mid = mid + Math.imul(al3, bh8) | 0;
mid = mid + Math.imul(ah3, bl8) | 0;
hi = hi + Math.imul(ah3, bh8) | 0;
lo = lo + Math.imul(al2, bl9) | 0;
mid = mid + Math.imul(al2, bh9) | 0;
mid = mid + Math.imul(ah2, bl9) | 0;
hi = hi + Math.imul(ah2, bh9) | 0;
var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
w11 &= 0x3ffffff;
/* k = 12 */ lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = mid + Math.imul(ah9, bl3) | 0;
hi = Math.imul(ah9, bh3);
lo = lo + Math.imul(al8, bl4) | 0;
mid = mid + Math.imul(al8, bh4) | 0;
mid = mid + Math.imul(ah8, bl4) | 0;
hi = hi + Math.imul(ah8, bh4) | 0;
lo = lo + Math.imul(al7, bl5) | 0;
mid = mid + Math.imul(al7, bh5) | 0;
mid = mid + Math.imul(ah7, bl5) | 0;
hi = hi + Math.imul(ah7, bh5) | 0;
lo = lo + Math.imul(al6, bl6) | 0;
mid = mid + Math.imul(al6, bh6) | 0;
mid = mid + Math.imul(ah6, bl6) | 0;
hi = hi + Math.imul(ah6, bh6) | 0;
lo = lo + Math.imul(al5, bl7) | 0;
mid = mid + Math.imul(al5, bh7) | 0;
mid = mid + Math.imul(ah5, bl7) | 0;
hi = hi + Math.imul(ah5, bh7) | 0;
lo = lo + Math.imul(al4, bl8) | 0;
mid = mid + Math.imul(al4, bh8) | 0;
mid = mid + Math.imul(ah4, bl8) | 0;
hi = hi + Math.imul(ah4, bh8) | 0;
lo = lo + Math.imul(al3, bl9) | 0;
mid = mid + Math.imul(al3, bh9) | 0;
mid = mid + Math.imul(ah3, bl9) | 0;
hi = hi + Math.imul(ah3, bh9) | 0;
var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
w12 &= 0x3ffffff;
/* k = 13 */ lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = mid + Math.imul(ah9, bl4) | 0;
hi = Math.imul(ah9, bh4);
lo = lo + Math.imul(al8, bl5) | 0;
mid = mid + Math.imul(al8, bh5) | 0;
mid = mid + Math.imul(ah8, bl5) | 0;
hi = hi + Math.imul(ah8, bh5) | 0;
lo = lo + Math.imul(al7, bl6) | 0;
mid = mid + Math.imul(al7, bh6) | 0;
mid = mid + Math.imul(ah7, bl6) | 0;
hi = hi + Math.imul(ah7, bh6) | 0;
lo = lo + Math.imul(al6, bl7) | 0;
mid = mid + Math.imul(al6, bh7) | 0;
mid = mid + Math.imul(ah6, bl7) | 0;
hi = hi + Math.imul(ah6, bh7) | 0;
lo = lo + Math.imul(al5, bl8) | 0;
mid = mid + Math.imul(al5, bh8) | 0;
mid = mid + Math.imul(ah5, bl8) | 0;
hi = hi + Math.imul(ah5, bh8) | 0;
lo = lo + Math.imul(al4, bl9) | 0;
mid = mid + Math.imul(al4, bh9) | 0;
mid = mid + Math.imul(ah4, bl9) | 0;
hi = hi + Math.imul(ah4, bh9) | 0;
var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
w13 &= 0x3ffffff;
/* k = 14 */ lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = mid + Math.imul(ah9, bl5) | 0;
hi = Math.imul(ah9, bh5);
lo = lo + Math.imul(al8, bl6) | 0;
mid = mid + Math.imul(al8, bh6) | 0;
mid = mid + Math.imul(ah8, bl6) | 0;
hi = hi + Math.imul(ah8, bh6) | 0;
lo = lo + Math.imul(al7, bl7) | 0;
mid = mid + Math.imul(al7, bh7) | 0;
mid = mid + Math.imul(ah7, bl7) | 0;
hi = hi + Math.imul(ah7, bh7) | 0;
lo = lo + Math.imul(al6, bl8) | 0;
mid = mid + Math.imul(al6, bh8) | 0;
mid = mid + Math.imul(ah6, bl8) | 0;
hi = hi + Math.imul(ah6, bh8) | 0;
lo = lo + Math.imul(al5, bl9) | 0;
mid = mid + Math.imul(al5, bh9) | 0;
mid = mid + Math.imul(ah5, bl9) | 0;
hi = hi + Math.imul(ah5, bh9) | 0;
var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
w14 &= 0x3ffffff;
/* k = 15 */ lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = mid + Math.imul(ah9, bl6) | 0;
hi = Math.imul(ah9, bh6);
lo = lo + Math.imul(al8, bl7) | 0;
mid = mid + Math.imul(al8, bh7) | 0;
mid = mid + Math.imul(ah8, bl7) | 0;
hi = hi + Math.imul(ah8, bh7) | 0;
lo = lo + Math.imul(al7, bl8) | 0;
mid = mid + Math.imul(al7, bh8) | 0;
mid = mid + Math.imul(ah7, bl8) | 0;
hi = hi + Math.imul(ah7, bh8) | 0;
lo = lo + Math.imul(al6, bl9) | 0;
mid = mid + Math.imul(al6, bh9) | 0;
mid = mid + Math.imul(ah6, bl9) | 0;
hi = hi + Math.imul(ah6, bh9) | 0;
var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
w15 &= 0x3ffffff;
/* k = 16 */ lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = mid + Math.imul(ah9, bl7) | 0;
hi = Math.imul(ah9, bh7);
lo = lo + Math.imul(al8, bl8) | 0;
mid = mid + Math.imul(al8, bh8) | 0;
mid = mid + Math.imul(ah8, bl8) | 0;
hi = hi + Math.imul(ah8, bh8) | 0;
lo = lo + Math.imul(al7, bl9) | 0;
mid = mid + Math.imul(al7, bh9) | 0;
mid = mid + Math.imul(ah7, bl9) | 0;
hi = hi + Math.imul(ah7, bh9) | 0;
var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
w16 &= 0x3ffffff;
/* k = 17 */ lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = mid + Math.imul(ah9, bl8) | 0;
hi = Math.imul(ah9, bh8);
lo = lo + Math.imul(al8, bl9) | 0;
mid = mid + Math.imul(al8, bh9) | 0;
mid = mid + Math.imul(ah8, bl9) | 0;
hi = hi + Math.imul(ah8, bh9) | 0;
var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
w17 &= 0x3ffffff;
/* k = 18 */ lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = mid + Math.imul(ah9, bl9) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0;
c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) comb10MulTo = smallMulTo;
function bigMulTo(self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for(var k = 0; k < out.length - 1; k++){
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for(var j = Math.max(0, k - self.length + 1); j <= maxJ; j++){
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = ncarry + (r / 0x4000000 | 0) | 0;
lo = lo + rword | 0;
rword = lo & 0x3ffffff;
ncarry = ncarry + (lo >>> 26) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) out.words[k] = carry;
else out.length--;
return out._strip();
}
function jumboMulTo(self, num, out) {
// Temporary disable, see https://github.com/indutny/bn.js/issues/211
// var fftm = new FFTM();
// return fftm.mulp(self, num, out);
return bigMulTo(self, num, out);
}
BN.prototype.mulTo = function mulTo(num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) res = comb10MulTo(this, num, out);
else if (len < 63) res = smallMulTo(this, num, out);
else if (len < 1024) res = bigMulTo(this, num, out);
else res = jumboMulTo(this, num, out);
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM(x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT(N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for(var i = 0; i < N; i++)t[i] = this.revBin(i, l, N);
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin(x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for(var i = 0; i < l; i++){
rb |= (x & 1) << l - i - 1;
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) {
for(var i = 0; i < N; i++){
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for(var s = 1; s < N; s <<= 1){
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for(var p = 0; p < N; p += l){
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for(var j = 0; j < s; j++){
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */ if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b(n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for(N = N / 2 | 0; N; N = N >>> 1)i++;
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate(rws, iws, N) {
if (N <= 1) return;
for(var i = 0; i < N / 2; i++){
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b(ws, N) {
var carry = 0;
for(var i = 0; i < N / 2; i++){
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) carry = 0;
else carry = w / 0x4000000 | 0;
}
return ws;
};
FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) {
var carry = 0;
for(var i = 0; i < len; i++){
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff;
carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff;
carry = carry >>> 13;
}
// Pad with zeroes
for(i = 2 * len; i < N; ++i)rws[i] = 0;
assert(carry === 0);
assert((carry & -8192) === 0);
};
FFTM.prototype.stub = function stub(N) {
var ph = new Array(N);
for(var i = 0; i < N; i++)ph[i] = 0;
return ph;
};
FFTM.prototype.mulp = function mulp(x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for(var i = 0; i < N; i++){
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out._strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul(num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(typeof num === "number");
assert(num < 0x4000000);
// Carry
var carry = 0;
for(var i = 0; i < this.length; i++){
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += w / 0x4000000 | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return isNegNum ? this.ineg() : this;
};
BN.prototype.muln = function muln(num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr() {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr() {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow(num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for(var i = 0; i < w.length; i++, res = res.sqr()){
if (w[i] !== 0) break;
}
if (++i < w.length) for(var q = res.sqr(); i < w.length; i++, q = q.sqr()){
if (w[i] === 0) continue;
res = res.mul(q);
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln(bits) {
assert(typeof bits === "number" && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = 0x3ffffff >>> 26 - r << 26 - r;
var i;
if (r !== 0) {
var carry = 0;
for(i = 0; i < this.length; i++){
var newCarry = this.words[i] & carryMask;
var c = (this.words[i] | 0) - newCarry << r;
this.words[i] = c | carry;
carry = newCarry >>> 26 - r;
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for(i = this.length - 1; i >= 0; i--)this.words[i + s] = this.words[i];
for(i = 0; i < s; i++)this.words[i] = 0;
this.length += s;
}
return this._strip();
};
BN.prototype.ishln = function ishln(bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn(bits, hint, extended) {
assert(typeof bits === "number" && bits >= 0);
var h;
if (hint) h = (hint - hint % 26) / 26;
else h = 0;
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for(var i = 0; i < s; i++)maskedWords.words[i] = this.words[i];
maskedWords.length = s;
}
if (s === 0) ;
else if (this.length > s) {
this.length -= s;
for(i = 0; i < this.length; i++)this.words[i] = this.words[i + s];
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for(i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--){
var word = this.words[i] | 0;
this.words[i] = carry << 26 - r | word >>> r;
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) maskedWords.words[maskedWords.length++] = carry;
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this._strip();
};
BN.prototype.ishrn = function ishrn(bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln(bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln(bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn(bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn(bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn(bit) {
assert(typeof bit === "number" && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn(bits) {
assert(typeof bits === "number" && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, "imaskn works only with positive numbers");
if (this.length <= s) return this;
if (r !== 0) s++;
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ 0x3ffffff >>> r << r;
this.words[this.length - 1] &= mask;
}
return this._strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn(bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn(num) {
assert(typeof num === "number");
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) <= num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn(num) {
this.words[0] += num;
// Carry
for(var i = 0; i < this.length && this.words[i] >= 0x4000000; i++){
this.words[i] -= 0x4000000;
if (i === this.length - 1) this.words[i + 1] = 1;
else this.words[i + 1]++;
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn(num) {
assert(typeof num === "number");
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else // Carry
for(var i = 0; i < this.length && this.words[i] < 0; i++){
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
return this._strip();
};
BN.prototype.addn = function addn(num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn(num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs() {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs() {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for(i = 0; i < num.length; i++){
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - (right / 0x4000000 | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for(; i < this.length - shift; i++){
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this._strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for(i = 0; i < this.length; i++){
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this._strip();
};
BN.prototype._wordDiv = function _wordDiv(num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== "mod") {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for(var i = 0; i < q.length; i++)q.words[i] = 0;
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) q.words[m] = 1;
}
for(var j = m - 1; j >= 0; j--){
var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min(qj / bhi | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while(a.negative !== 0){
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) a.negative ^= 1;
}
if (q) q.words[j] = qj;
}
if (q) q._strip();
a._strip();
// Denormalize
if (mode !== "div" && shift !== 0) a.iushrn(shift);
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod(num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) return {
div: new BN(0),
mod: new BN(0)
};
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== "mod") div = res.div.neg();
if (mode !== "div") {
mod = res.mod.neg();
if (positive && mod.negative !== 0) mod.iadd(num);
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== "mod") div = res.div.neg();
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== "div") {
mod = res.mod.neg();
if (positive && mod.negative !== 0) mod.isub(num);
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) return {
div: new BN(0),
mod: this
};
// Very short reduction
if (num.length === 1) {
if (mode === "div") return {
div: this.divn(num.words[0]),
mod: null
};
if (mode === "mod") return {
div: null,
mod: new BN(this.modrn(num.words[0]))
};
return {
div: this.divn(num.words[0]),
mod: new BN(this.modrn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div(num) {
return this.divmod(num, "div", false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod(num) {
return this.divmod(num, "mod", false).mod;
};
BN.prototype.umod = function umod(num) {
return this.divmod(num, "mod", true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound(num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modrn = function modrn(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var p = 67108864 % num;
var acc = 0;
for(var i = this.length - 1; i >= 0; i--)acc = (p * acc + (this.words[i] | 0)) % num;
return isNegNum ? -acc : acc;
};
// WARNING: DEPRECATED
BN.prototype.modn = function modn(num) {
return this.modrn(num);
};
// In-place division by number
BN.prototype.idivn = function idivn(num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var carry = 0;
for(var i = this.length - 1; i >= 0; i--){
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = w / num | 0;
carry = w % num;
}
this._strip();
return isNegNum ? this.ineg() : this;
};
BN.prototype.divn = function divn(num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd(p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) x = x.umod(p);
else x = x.clone();
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while(x.isEven() && y.isEven()){
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while(!x.isZero()){
for(var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while(i-- > 0){
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for(var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while(j-- > 0){
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp(p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) a = a.umod(p);
else a = a.clone();
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while(a.cmpn(1) > 0 && b.cmpn(1) > 0){
for(var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while(i-- > 0){
if (x1.isOdd()) x1.iadd(delta);
x1.iushrn(1);
}
}
for(var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while(j-- > 0){
if (x2.isOdd()) x2.iadd(delta);
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) res = x1;
else res = x2;
if (res.cmpn(0) < 0) res.iadd(p);
return res;
};
BN.prototype.gcd = function gcd(num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for(var shift = 0; a.isEven() && b.isEven(); shift++){
a.iushrn(1);
b.iushrn(1);
}
do {
while(a.isEven())a.iushrn(1);
while(b.isEven())b.iushrn(1);
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) break;
a.isub(b);
}while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm(num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven() {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd() {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln(num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn(bit) {
assert(typeof bit === "number");
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for(var i = s; carry !== 0 && i < this.length; i++){
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero() {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn(num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this._strip();
var res;
if (this.length > 1) res = 1;
else {
if (negative) num = -num;
assert(num <= 0x3ffffff, "Number is too big");
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp(num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp(num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for(var i = this.length - 1; i >= 0; i--){
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) res = -1;
else if (a > b) res = 1;
break;
}
return res;
};
BN.prototype.gtn = function gtn(num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt(num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten(num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte(num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn(num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt(num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten(num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte(num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn(num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq(num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red(num) {
return new Red(num);
};
BN.prototype.toRed = function toRed(ctx) {
assert(!this.red, "Already a number in reduction context");
assert(this.negative === 0, "red works only with positives");
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed() {
assert(this.red, "fromRed works only with numbers in reduction context");
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed(ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed(ctx) {
assert(!this.red, "Already a number in reduction context");
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd(num) {
assert(this.red, "redAdd works only with red numbers");
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd(num) {
assert(this.red, "redIAdd works only with red numbers");
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub(num) {
assert(this.red, "redSub works only with red numbers");
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub(num) {
assert(this.red, "redISub works only with red numbers");
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl(num) {
assert(this.red, "redShl works only with red numbers");
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul(num) {
assert(this.red, "redMul works only with red numbers");
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul(num) {
assert(this.red, "redMul works only with red numbers");
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr() {
assert(this.red, "redSqr works only with red numbers");
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr() {
assert(this.red, "redISqr works only with red numbers");
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt() {
assert(this.red, "redSqrt works only with red numbers");
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm() {
assert(this.red, "redInvm works only with red numbers");
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg() {
assert(this.red, "redNeg works only with red numbers");
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow(num) {
assert(this.red && !num.red, "redPow(normalNum)");
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime(name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp() {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce(num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
}while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) r.isub(this.p);
else if (r.strip !== undefined) // r is a BN v4 instance
r.strip();
else // r is a BN v5 instance
r._strip();
return r;
};
MPrime.prototype.split = function split(input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK(num) {
return num.imul(this.k);
};
function K256() {
MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
}
inherits(K256, MPrime);
K256.prototype.split = function split(input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for(var i = 0; i < outLen; i++)output.words[i] = input.words[i];
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for(i = 10; i < input.length; i++){
var next = input.words[i] | 0;
input.words[i - 10] = (next & mask) << 4 | prev >>> 22;
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) input.length -= 10;
else input.length -= 9;
};
K256.prototype.imulK = function imulK(num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for(var i = 0; i < num.length; i++){
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + (lo / 0x4000000 | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) num.length--;
}
return num;
};
function P224() {
MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
}
inherits(P224, MPrime);
function P192() {
MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
}
inherits(P192, MPrime);
function P25519() {
// 2 ^ 255 - 19
MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK(num) {
// K = 0x13
var carry = 0;
for(var i = 0; i < num.length; i++){
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) num.words[num.length++] = carry;
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime(name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === "k256") prime = new K256();
else if (name === "p224") prime = new P224();
else if (name === "p192") prime = new P192();
else if (name === "p25519") prime = new P25519();
else throw new Error("Unknown prime " + name);
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red(m) {
if (typeof m === "string") {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), "modulus must be greater than 1");
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1(a) {
assert(a.negative === 0, "red works only with positives");
assert(a.red, "red works only with red numbers");
};
Red.prototype._verify2 = function _verify2(a, b) {
assert((a.negative | b.negative) === 0, "red works only with positives");
assert(a.red && a.red === b.red, "red works only with red numbers");
};
Red.prototype.imod = function imod(a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
move(a, a.umod(this.m)._forceRed(this));
return a;
};
Red.prototype.neg = function neg(a) {
if (a.isZero()) return a.clone();
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add(a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) res.isub(this.m);
return res._forceRed(this);
};
Red.prototype.iadd = function iadd(a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) res.isub(this.m);
return res;
};
Red.prototype.sub = function sub(a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) res.iadd(this.m);
return res._forceRed(this);
};
Red.prototype.isub = function isub(a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) res.iadd(this.m);
return res;
};
Red.prototype.shl = function shl(a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul(a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul(a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr(a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr(a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt(a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while(!q.isZero() && q.andln(1) === 0){
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while(this.pow(z, lpow).cmp(nOne) !== 0)z.redIAdd(nOne);
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while(t.cmp(one) !== 0){
var tmp = t;
for(var i = 0; tmp.cmp(one) !== 0; i++)tmp = tmp.redSqr();
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm(a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else return this.imod(inv);
};
Red.prototype.pow = function pow(a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for(var i = 2; i < wnd.length; i++)wnd[i] = this.mul(wnd[i - 1], a);
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) start = 26;
for(i = num.length - 1; i >= 0; i--){
var word = num.words[i];
for(var j = start - 1; j >= 0; j--){
var bit = word >> j & 1;
if (res !== wnd[0]) res = this.sqr(res);
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo(num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom(num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont(num) {
return new Mont(num);
};
function Mont(m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) this.shift += 26 - this.shift % 26;
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo(num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom(num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul(a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) res = u.isub(this.m);
else if (u.cmpn(0) < 0) res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.mul = function mul(a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) res = u.isub(this.m);
else if (u.cmpn(0) < 0) res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.invm = function invm(a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(module, this);
},{"buffer":"jhUEF"}],"jJQ5a":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.signTransaction = exports.createTransaction = exports.SCHEMA = exports.Action = exports.SignedTransaction = exports.Transaction = exports.Signature = exports.deleteAccount = exports.deleteKey = exports.addKey = exports.stake = exports.transfer = exports.functionCall = exports.stringifyJsonOrBytes = exports.deployContract = exports.createAccount = exports.DeleteAccount = exports.DeleteKey = exports.AddKey = exports.Stake = exports.Transfer = exports.FunctionCall = exports.DeployContract = exports.CreateAccount = exports.IAction = exports.functionCallAccessKey = exports.fullAccessKey = exports.AccessKey = exports.AccessKeyPermission = exports.FullAccessPermission = exports.FunctionCallPermission = void 0;
const js_sha256_1 = __importDefault(require("js-sha256"));
const enums_1 = require("./utils/enums");
const borsh_1 = require("borsh");
const key_pair_1 = require("./utils/key_pair");
class FunctionCallPermission extends enums_1.Assignable {
}
exports.FunctionCallPermission = FunctionCallPermission;
class FullAccessPermission extends enums_1.Assignable {
}
exports.FullAccessPermission = FullAccessPermission;
class AccessKeyPermission extends enums_1.Enum {
}
exports.AccessKeyPermission = AccessKeyPermission;
class AccessKey extends enums_1.Assignable {
}
exports.AccessKey = AccessKey;
function fullAccessKey() {
return new AccessKey({
nonce: 0,
permission: new AccessKeyPermission({
fullAccess: new FullAccessPermission({})
})
});
}
exports.fullAccessKey = fullAccessKey;
function functionCallAccessKey(receiverId, methodNames, allowance) {
return new AccessKey({
nonce: 0,
permission: new AccessKeyPermission({
functionCall: new FunctionCallPermission({
receiverId,
allowance,
methodNames
})
})
});
}
exports.functionCallAccessKey = functionCallAccessKey;
class IAction extends enums_1.Assignable {
}
exports.IAction = IAction;
class CreateAccount extends IAction {
}
exports.CreateAccount = CreateAccount;
class DeployContract extends IAction {
}
exports.DeployContract = DeployContract;
class FunctionCall extends IAction {
}
exports.FunctionCall = FunctionCall;
class Transfer extends IAction {
}
exports.Transfer = Transfer;
class Stake extends IAction {
}
exports.Stake = Stake;
class AddKey extends IAction {
}
exports.AddKey = AddKey;
class DeleteKey extends IAction {
}
exports.DeleteKey = DeleteKey;
class DeleteAccount extends IAction {
}
exports.DeleteAccount = DeleteAccount;
function createAccount() {
return new Action({
createAccount: new CreateAccount({})
});
}
exports.createAccount = createAccount;
function deployContract(code) {
return new Action({
deployContract: new DeployContract({
code
})
});
}
exports.deployContract = deployContract;
function stringifyJsonOrBytes(args) {
const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length;
const serializedArgs = isUint8Array ? args : Buffer.from(JSON.stringify(args));
return serializedArgs;
}
exports.stringifyJsonOrBytes = stringifyJsonOrBytes;
/**
* Constructs {@link Action} instance representing contract method call.
*
* @param methodName the name of the method to call
* @param args arguments to pass to method. Can be either plain JS object which gets serialized as JSON automatically
* or `Uint8Array` instance which represents bytes passed as is.
* @param gas max amount of gas that method call can use
* @param deposit amount of NEAR (in yoctoNEAR) to send together with the call
* @param stringify Convert input arguments into bytes array.
*/ function functionCall(methodName, args, gas, deposit, stringify = stringifyJsonOrBytes) {
return new Action({
functionCall: new FunctionCall({
methodName,
args: stringify(args),
gas,
deposit
})
});
}
exports.functionCall = functionCall;
function transfer(deposit) {
return new Action({
transfer: new Transfer({
deposit
})
});
}
exports.transfer = transfer;
function stake(stake, publicKey) {
return new Action({
stake: new Stake({
stake,
publicKey
})
});
}
exports.stake = stake;
function addKey(publicKey, accessKey) {
return new Action({
addKey: new AddKey({
publicKey,
accessKey
})
});
}
exports.addKey = addKey;
function deleteKey(publicKey) {
return new Action({
deleteKey: new DeleteKey({
publicKey
})
});
}
exports.deleteKey = deleteKey;
function deleteAccount(beneficiaryId) {
return new Action({
deleteAccount: new DeleteAccount({
beneficiaryId
})
});
}
exports.deleteAccount = deleteAccount;
class Signature extends enums_1.Assignable {
}
exports.Signature = Signature;
class Transaction extends enums_1.Assignable {
encode() {
return borsh_1.serialize(exports.SCHEMA, this);
}
static decode(bytes) {
return borsh_1.deserialize(exports.SCHEMA, Transaction, bytes);
}
}
exports.Transaction = Transaction;
class SignedTransaction extends enums_1.Assignable {
encode() {
return borsh_1.serialize(exports.SCHEMA, this);
}
static decode(bytes) {
return borsh_1.deserialize(exports.SCHEMA, SignedTransaction, bytes);
}
}
exports.SignedTransaction = SignedTransaction;
/**
* Contains a list of the valid transaction Actions available with this API
* @see {@link https://nomicon.io/RuntimeSpec/Actions.html | Actions Spec}
*/ class Action extends enums_1.Enum {
}
exports.Action = Action;
exports.SCHEMA = new Map([
[
Signature,
{
kind: "struct",
fields: [
[
"keyType",
"u8"
],
[
"data",
[
64
]
]
]
}
],
[
SignedTransaction,
{
kind: "struct",
fields: [
[
"transaction",
Transaction
],
[
"signature",
Signature
]
]
}
],
[
Transaction,
{
kind: "struct",
fields: [
[
"signerId",
"string"
],
[
"publicKey",
key_pair_1.PublicKey
],
[
"nonce",
"u64"
],
[
"receiverId",
"string"
],
[
"blockHash",
[
32
]
],
[
"actions",
[
Action
]
]
]
}
],
[
key_pair_1.PublicKey,
{
kind: "struct",
fields: [
[
"keyType",
"u8"
],
[
"data",
[
32
]
]
]
}
],
[
AccessKey,
{
kind: "struct",
fields: [
[
"nonce",
"u64"
],
[
"permission",
AccessKeyPermission
],
]
}
],
[
AccessKeyPermission,
{
kind: "enum",
field: "enum",
values: [
[
"functionCall",
FunctionCallPermission
],
[
"fullAccess",
FullAccessPermission
],
]
}
],
[
FunctionCallPermission,
{
kind: "struct",
fields: [
[
"allowance",
{
kind: "option",
type: "u128"
}
],
[
"receiverId",
"string"
],
[
"methodNames",
[
"string"
]
],
]
}
],
[
FullAccessPermission,
{
kind: "struct",
fields: []
}
],
[
Action,
{
kind: "enum",
field: "enum",
values: [
[
"createAccount",
CreateAccount
],
[
"deployContract",
DeployContract
],
[
"functionCall",
FunctionCall
],
[
"transfer",
Transfer
],
[
"stake",
Stake
],
[
"addKey",
AddKey
],
[
"deleteKey",
DeleteKey
],
[
"deleteAccount",
DeleteAccount
],
]
}
],
[
CreateAccount,
{
kind: "struct",
fields: []
}
],
[
DeployContract,
{
kind: "struct",
fields: [
[
"code",
[
"u8"
]
]
]
}
],
[
FunctionCall,
{
kind: "struct",
fields: [
[
"methodName",
"string"
],
[
"args",
[
"u8"
]
],
[
"gas",
"u64"
],
[
"deposit",
"u128"
]
]
}
],
[
Transfer,
{
kind: "struct",
fields: [
[
"deposit",
"u128"
]
]
}
],
[
Stake,
{
kind: "struct",
fields: [
[
"stake",
"u128"
],
[
"publicKey",
key_pair_1.PublicKey
]
]
}
],
[
AddKey,
{
kind: "struct",
fields: [
[
"publicKey",
key_pair_1.PublicKey
],
[
"accessKey",
AccessKey
]
]
}
],
[
DeleteKey,
{
kind: "struct",
fields: [
[
"publicKey",
key_pair_1.PublicKey
]
]
}
],
[
DeleteAccount,
{
kind: "struct",
fields: [
[
"beneficiaryId",
"string"
]
]
}
],
]);
function createTransaction(signerId, publicKey, receiverId, nonce, actions, blockHash) {
return new Transaction({
signerId,
publicKey,
nonce,
receiverId,
actions,
blockHash
});
}
exports.createTransaction = createTransaction;
/**
* Signs a given transaction from an account with given keys, applied to the given network
* @param transaction The Transaction object to sign
* @param signer The {Signer} object that assists with signing keys
* @param accountId The human-readable NEAR account name
* @param networkId The targeted network. (ex. default, betanet, etc…)
*/ async function signTransactionObject(transaction, signer, accountId, networkId) {
const message = borsh_1.serialize(exports.SCHEMA, transaction);
const hash = new Uint8Array(js_sha256_1.default.sha256.array(message));
const signature = await signer.signMessage(message, accountId, networkId);
const signedTx = new SignedTransaction({
transaction,
signature: new Signature({
keyType: transaction.publicKey.keyType,
data: signature.signature
})
});
return [
hash,
signedTx
];
}
async function signTransaction(...args) {
if (args[0].constructor === Transaction) {
const [transaction, signer, accountId, networkId] = args;
return signTransactionObject(transaction, signer, accountId, networkId);
} else {
const [receiverId, nonce, actions, blockHash, signer1, accountId1, networkId1] = args;
const publicKey = await signer1.getPublicKey(accountId1, networkId1);
const transaction1 = createTransaction(accountId1, publicKey, receiverId, nonce, actions, blockHash);
return signTransactionObject(transaction1, signer1, accountId1, networkId1);
}
}
exports.signTransaction = signTransaction;
},{"buffer":"dvCeB","js-sha256":"ahVaM","./utils/enums":"kjmPo","borsh":"4JCmN","./utils/key_pair":"kBQFP"}],"ahVaM":[function(require,module,exports) {
var process = require("process");
var global = arguments[3];
/**
* [js-sha256]{@link https://github.com/emn178/js-sha256}
*
* @version 0.9.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*/ /*jslint bitwise: true */ (function() {
"use strict";
var ERROR = "input is invalid type";
var WINDOW = typeof window === "object";
var root = WINDOW ? window : {};
if (root.JS_SHA256_NO_WINDOW) WINDOW = false;
var WEB_WORKER = !WINDOW && typeof self === "object";
var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node;
if (NODE_JS) root = global;
else if (WEB_WORKER) root = self;
var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && true && module.exports;
var AMD = typeof define === "function" && define.amd;
var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined";
var HEX_CHARS = "0123456789abcdef".split("");
var EXTRA = [
-2147483648,
8388608,
32768,
128
];
var SHIFT = [
24,
16,
8,
0
];
var K = [
0x428a2f98,
0x71374491,
0xb5c0fbcf,
0xe9b5dba5,
0x3956c25b,
0x59f111f1,
0x923f82a4,
0xab1c5ed5,
0xd807aa98,
0x12835b01,
0x243185be,
0x550c7dc3,
0x72be5d74,
0x80deb1fe,
0x9bdc06a7,
0xc19bf174,
0xe49b69c1,
0xefbe4786,
0x0fc19dc6,
0x240ca1cc,
0x2de92c6f,
0x4a7484aa,
0x5cb0a9dc,
0x76f988da,
0x983e5152,
0xa831c66d,
0xb00327c8,
0xbf597fc7,
0xc6e00bf3,
0xd5a79147,
0x06ca6351,
0x14292967,
0x27b70a85,
0x2e1b2138,
0x4d2c6dfc,
0x53380d13,
0x650a7354,
0x766a0abb,
0x81c2c92e,
0x92722c85,
0xa2bfe8a1,
0xa81a664b,
0xc24b8b70,
0xc76c51a3,
0xd192e819,
0xd6990624,
0xf40e3585,
0x106aa070,
0x19a4c116,
0x1e376c08,
0x2748774c,
0x34b0bcb5,
0x391c0cb3,
0x4ed8aa4a,
0x5b9cca4f,
0x682e6ff3,
0x748f82ee,
0x78a5636f,
0x84c87814,
0x8cc70208,
0x90befffa,
0xa4506ceb,
0xbef9a3f7,
0xc67178f2
];
var OUTPUT_TYPES = [
"hex",
"array",
"digest",
"arrayBuffer"
];
var blocks = [];
if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) ArrayBuffer.isView = function(obj) {
return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer;
};
var createOutputMethod = function(outputType, is224) {
return function(message) {
return new Sha256(is224, true).update(message)[outputType]();
};
};
var createMethod = function(is224) {
var method = createOutputMethod("hex", is224);
if (NODE_JS) method = nodeWrap(method, is224);
method.create = function() {
return new Sha256(is224);
};
method.update = function(message) {
return method.create().update(message);
};
for(var i = 0; i < OUTPUT_TYPES.length; ++i){
var type = OUTPUT_TYPES[i];
method[type] = createOutputMethod(type, is224);
}
return method;
};
var nodeWrap = function(method, is224) {
var crypto = eval("require('crypto')");
var Buffer = eval("require('buffer').Buffer");
var algorithm = is224 ? "sha224" : "sha256";
var nodeMethod = function(message) {
if (typeof message === "string") return crypto.createHash(algorithm).update(message, "utf8").digest("hex");
else {
if (message === null || message === undefined) throw new Error(ERROR);
else if (message.constructor === ArrayBuffer) message = new Uint8Array(message);
}
if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) return crypto.createHash(algorithm).update(new Buffer(message)).digest("hex");
else return method(message);
};
return nodeMethod;
};
var createHmacOutputMethod = function(outputType, is224) {
return function(key, message) {
return new HmacSha256(key, is224, true).update(message)[outputType]();
};
};
var createHmacMethod = function(is224) {
var method = createHmacOutputMethod("hex", is224);
method.create = function(key) {
return new HmacSha256(key, is224);
};
method.update = function(key, message) {
return method.create(key).update(message);
};
for(var i = 0; i < OUTPUT_TYPES.length; ++i){
var type = OUTPUT_TYPES[i];
method[type] = createHmacOutputMethod(type, is224);
}
return method;
};
function Sha256(is224, sharedMemory) {
if (sharedMemory) {
blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
this.blocks = blocks;
} else this.blocks = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
];
if (is224) {
this.h0 = 0xc1059ed8;
this.h1 = 0x367cd507;
this.h2 = 0x3070dd17;
this.h3 = 0xf70e5939;
this.h4 = 0xffc00b31;
this.h5 = 0x68581511;
this.h6 = 0x64f98fa7;
this.h7 = 0xbefa4fa4;
} else {
this.h0 = 0x6a09e667;
this.h1 = 0xbb67ae85;
this.h2 = 0x3c6ef372;
this.h3 = 0xa54ff53a;
this.h4 = 0x510e527f;
this.h5 = 0x9b05688c;
this.h6 = 0x1f83d9ab;
this.h7 = 0x5be0cd19;
}
this.block = this.start = this.bytes = this.hBytes = 0;
this.finalized = this.hashed = false;
this.first = true;
this.is224 = is224;
}
Sha256.prototype.update = function(message) {
if (this.finalized) return;
var notString, type = typeof message;
if (type !== "string") {
if (type === "object") {
if (message === null) throw new Error(ERROR);
else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message);
else if (!Array.isArray(message)) {
if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR);
}
} else throw new Error(ERROR);
notString = true;
}
var code, index = 0, i, length = message.length, blocks = this.blocks;
while(index < length){
if (this.hashed) {
this.hashed = false;
blocks[0] = this.block;
blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
}
if (notString) for(i = this.start; index < length && i < 64; ++index)blocks[i >> 2] |= message[index] << SHIFT[(i++) & 3];
else for(i = this.start; index < length && i < 64; ++index){
code = message.charCodeAt(index);
if (code < 0x80) blocks[i >> 2] |= code << SHIFT[(i++) & 3];
else if (code < 0x800) {
blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[(i++) & 3];
} else if (code < 0xd800 || code >= 0xe000) {
blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[(i++) & 3];
} else {
code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[(i++) & 3];
blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[(i++) & 3];
}
}
this.lastByteIndex = i;
this.bytes += i - this.start;
if (i >= 64) {
this.block = blocks[16];
this.start = i - 64;
this.hash();
this.hashed = true;
} else this.start = i;
}
if (this.bytes > 4294967295) {
this.hBytes += this.bytes / 4294967296 << 0;
this.bytes = this.bytes % 4294967296;
}
return this;
};
Sha256.prototype.finalize = function() {
if (this.finalized) return;
this.finalized = true;
var blocks = this.blocks, i = this.lastByteIndex;
blocks[16] = this.block;
blocks[i >> 2] |= EXTRA[i & 3];
this.block = blocks[16];
if (i >= 56) {
if (!this.hashed) this.hash();
blocks[0] = this.block;
blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
}
blocks[14] = this.hBytes << 3 | this.bytes >>> 29;
blocks[15] = this.bytes << 3;
this.hash();
};
Sha256.prototype.hash = function() {
var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc;
for(j = 16; j < 64; ++j){
// rightrotate
t1 = blocks[j - 15];
s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3;
t1 = blocks[j - 2];
s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;
blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0;
}
bc = b & c;
for(j = 0; j < 64; j += 4){
if (this.first) {
if (this.is224) {
ab = 300032;
t1 = blocks[0] - 1413257819;
h = t1 - 150054599 << 0;
d = t1 + 24177077 << 0;
} else {
ab = 704751109;
t1 = blocks[0] - 210244248;
h = t1 - 1521486534 << 0;
d = t1 + 143694565 << 0;
}
this.first = false;
} else {
s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
ab = a & b;
maj = ab ^ a & c ^ bc;
ch = e & f ^ ~e & g;
t1 = h + s1 + ch + K[j] + blocks[j];
t2 = s0 + maj;
h = d + t1 << 0;
d = t1 + t2 << 0;
}
s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10);
s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7);
da = d & a;
maj = da ^ d & b ^ ab;
ch = h & e ^ ~h & f;
t1 = g + s1 + ch + K[j + 1] + blocks[j + 1];
t2 = s0 + maj;
g = c + t1 << 0;
c = t1 + t2 << 0;
s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10);
s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7);
cd = c & d;
maj = cd ^ c & a ^ da;
ch = g & h ^ ~g & e;
t1 = f + s1 + ch + K[j + 2] + blocks[j + 2];
t2 = s0 + maj;
f = b + t1 << 0;
b = t1 + t2 << 0;
s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10);
s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7);
bc = b & c;
maj = bc ^ b & d ^ cd;
ch = f & g ^ ~f & h;
t1 = e + s1 + ch + K[j + 3] + blocks[j + 3];
t2 = s0 + maj;
e = a + t1 << 0;
a = t1 + t2 << 0;
}
this.h0 = this.h0 + a << 0;
this.h1 = this.h1 + b << 0;
this.h2 = this.h2 + c << 0;
this.h3 = this.h3 + d << 0;
this.h4 = this.h4 + e << 0;
this.h5 = this.h5 + f << 0;
this.h6 = this.h6 + g << 0;
this.h7 = this.h7 + h << 0;
};
Sha256.prototype.hex = function() {
this.finalize();
var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
var hex = HEX_CHARS[h0 >> 28 & 0x0F] + HEX_CHARS[h0 >> 24 & 0x0F] + HEX_CHARS[h0 >> 20 & 0x0F] + HEX_CHARS[h0 >> 16 & 0x0F] + HEX_CHARS[h0 >> 12 & 0x0F] + HEX_CHARS[h0 >> 8 & 0x0F] + HEX_CHARS[h0 >> 4 & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[h1 >> 28 & 0x0F] + HEX_CHARS[h1 >> 24 & 0x0F] + HEX_CHARS[h1 >> 20 & 0x0F] + HEX_CHARS[h1 >> 16 & 0x0F] + HEX_CHARS[h1 >> 12 & 0x0F] + HEX_CHARS[h1 >> 8 & 0x0F] + HEX_CHARS[h1 >> 4 & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[h2 >> 28 & 0x0F] + HEX_CHARS[h2 >> 24 & 0x0F] + HEX_CHARS[h2 >> 20 & 0x0F] + HEX_CHARS[h2 >> 16 & 0x0F] + HEX_CHARS[h2 >> 12 & 0x0F] + HEX_CHARS[h2 >> 8 & 0x0F] + HEX_CHARS[h2 >> 4 & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[h3 >> 28 & 0x0F] + HEX_CHARS[h3 >> 24 & 0x0F] + HEX_CHARS[h3 >> 20 & 0x0F] + HEX_CHARS[h3 >> 16 & 0x0F] + HEX_CHARS[h3 >> 12 & 0x0F] + HEX_CHARS[h3 >> 8 & 0x0F] + HEX_CHARS[h3 >> 4 & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[h4 >> 28 & 0x0F] + HEX_CHARS[h4 >> 24 & 0x0F] + HEX_CHARS[h4 >> 20 & 0x0F] + HEX_CHARS[h4 >> 16 & 0x0F] + HEX_CHARS[h4 >> 12 & 0x0F] + HEX_CHARS[h4 >> 8 & 0x0F] + HEX_CHARS[h4 >> 4 & 0x0F] + HEX_CHARS[h4 & 0x0F] + HEX_CHARS[h5 >> 28 & 0x0F] + HEX_CHARS[h5 >> 24 & 0x0F] + HEX_CHARS[h5 >> 20 & 0x0F] + HEX_CHARS[h5 >> 16 & 0x0F] + HEX_CHARS[h5 >> 12 & 0x0F] + HEX_CHARS[h5 >> 8 & 0x0F] + HEX_CHARS[h5 >> 4 & 0x0F] + HEX_CHARS[h5 & 0x0F] + HEX_CHARS[h6 >> 28 & 0x0F] + HEX_CHARS[h6 >> 24 & 0x0F] + HEX_CHARS[h6 >> 20 & 0x0F] + HEX_CHARS[h6 >> 16 & 0x0F] + HEX_CHARS[h6 >> 12 & 0x0F] + HEX_CHARS[h6 >> 8 & 0x0F] + HEX_CHARS[h6 >> 4 & 0x0F] + HEX_CHARS[h6 & 0x0F];
if (!this.is224) hex += HEX_CHARS[h7 >> 28 & 0x0F] + HEX_CHARS[h7 >> 24 & 0x0F] + HEX_CHARS[h7 >> 20 & 0x0F] + HEX_CHARS[h7 >> 16 & 0x0F] + HEX_CHARS[h7 >> 12 & 0x0F] + HEX_CHARS[h7 >> 8 & 0x0F] + HEX_CHARS[h7 >> 4 & 0x0F] + HEX_CHARS[h7 & 0x0F];
return hex;
};
Sha256.prototype.toString = Sha256.prototype.hex;
Sha256.prototype.digest = function() {
this.finalize();
var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7;
var arr = [
h0 >> 24 & 0xFF,
h0 >> 16 & 0xFF,
h0 >> 8 & 0xFF,
h0 & 0xFF,
h1 >> 24 & 0xFF,
h1 >> 16 & 0xFF,
h1 >> 8 & 0xFF,
h1 & 0xFF,
h2 >> 24 & 0xFF,
h2 >> 16 & 0xFF,
h2 >> 8 & 0xFF,
h2 & 0xFF,
h3 >> 24 & 0xFF,
h3 >> 16 & 0xFF,
h3 >> 8 & 0xFF,
h3 & 0xFF,
h4 >> 24 & 0xFF,
h4 >> 16 & 0xFF,
h4 >> 8 & 0xFF,
h4 & 0xFF,
h5 >> 24 & 0xFF,
h5 >> 16 & 0xFF,
h5 >> 8 & 0xFF,
h5 & 0xFF,
h6 >> 24 & 0xFF,
h6 >> 16 & 0xFF,
h6 >> 8 & 0xFF,
h6 & 0xFF
];
if (!this.is224) arr.push(h7 >> 24 & 0xFF, h7 >> 16 & 0xFF, h7 >> 8 & 0xFF, h7 & 0xFF);
return arr;
};
Sha256.prototype.array = Sha256.prototype.digest;
Sha256.prototype.arrayBuffer = function() {
this.finalize();
var buffer = new ArrayBuffer(this.is224 ? 28 : 32);
var dataView = new DataView(buffer);
dataView.setUint32(0, this.h0);
dataView.setUint32(4, this.h1);
dataView.setUint32(8, this.h2);
dataView.setUint32(12, this.h3);
dataView.setUint32(16, this.h4);
dataView.setUint32(20, this.h5);
dataView.setUint32(24, this.h6);
if (!this.is224) dataView.setUint32(28, this.h7);
return buffer;
};
function HmacSha256(key, is224, sharedMemory) {
var i, type = typeof key;
if (type === "string") {
var bytes = [], length = key.length, index = 0, code;
for(i = 0; i < length; ++i){
code = key.charCodeAt(i);
if (code < 0x80) bytes[index++] = code;
else if (code < 0x800) {
bytes[index++] = 0xc0 | code >> 6;
bytes[index++] = 0x80 | code & 0x3f;
} else if (code < 0xd800 || code >= 0xe000) {
bytes[index++] = 0xe0 | code >> 12;
bytes[index++] = 0x80 | code >> 6 & 0x3f;
bytes[index++] = 0x80 | code & 0x3f;
} else {
code = 0x10000 + ((code & 0x3ff) << 10 | key.charCodeAt(++i) & 0x3ff);
bytes[index++] = 0xf0 | code >> 18;
bytes[index++] = 0x80 | code >> 12 & 0x3f;
bytes[index++] = 0x80 | code >> 6 & 0x3f;
bytes[index++] = 0x80 | code & 0x3f;
}
}
key = bytes;
} else {
if (type === "object") {
if (key === null) throw new Error(ERROR);
else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) key = new Uint8Array(key);
else if (!Array.isArray(key)) {
if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) throw new Error(ERROR);
}
} else throw new Error(ERROR);
}
if (key.length > 64) key = new Sha256(is224, true).update(key).array();
var oKeyPad = [], iKeyPad = [];
for(i = 0; i < 64; ++i){
var b = key[i] || 0;
oKeyPad[i] = 0x5c ^ b;
iKeyPad[i] = 0x36 ^ b;
}
Sha256.call(this, is224, sharedMemory);
this.update(iKeyPad);
this.oKeyPad = oKeyPad;
this.inner = true;
this.sharedMemory = sharedMemory;
}
HmacSha256.prototype = new Sha256();
HmacSha256.prototype.finalize = function() {
Sha256.prototype.finalize.call(this);
if (this.inner) {
this.inner = false;
var innerHash = this.array();
Sha256.call(this, this.is224, this.sharedMemory);
this.update(this.oKeyPad);
this.update(innerHash);
Sha256.prototype.finalize.call(this);
}
};
var exports = createMethod();
exports.sha256 = exports;
exports.sha224 = createMethod(true);
exports.sha256.hmac = createHmacMethod();
exports.sha224.hmac = createHmacMethod(true);
if (COMMON_JS) module.exports = exports;
else {
root.sha256 = exports.sha256;
root.sha224 = exports.sha224;
if (AMD) define(function() {
return exports;
});
}
})();
},{"process":"d5jf4"}],"d5jf4":[function(require,module,exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
throw new Error("clearTimeout has not been defined");
}
(function() {
try {
if (typeof setTimeout === "function") cachedSetTimeout = setTimeout;
else cachedSetTimeout = defaultSetTimout;
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === "function") cachedClearTimeout = clearTimeout;
else cachedClearTimeout = defaultClearTimeout;
} catch (e1) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) //normal enviroments in sane situations
return setTimeout(fun, 0);
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e1) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) //normal enviroments in sane situations
return clearTimeout(marker);
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e1) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) return;
draining = false;
if (currentQueue.length) queue = currentQueue.concat(queue);
else queueIndex = -1;
if (queue.length) drainQueue();
}
function drainQueue() {
if (draining) return;
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len){
currentQueue = queue;
queue = [];
while(++queueIndex < len)if (currentQueue) currentQueue[queueIndex].run();
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) for(var i = 1; i < arguments.length; i++)args[i - 1] = arguments[i];
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) runTimeout(drainQueue);
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function() {
this.fun.apply(null, this.array);
};
process.title = "browser";
process.browser = true;
process.env = {};
process.argv = [];
process.version = ""; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function(name) {
return [];
};
process.binding = function(name) {
throw new Error("process.binding is not supported");
};
process.cwd = function() {
return "/";
};
process.chdir = function(dir) {
throw new Error("process.chdir is not supported");
};
process.umask = function() {
return 0;
};
},{}],"6CFD9":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.diffEpochValidators = exports.findSeatPrice = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const depd_1 = __importDefault(require("depd"));
/** Finds seat price given validators stakes and number of seats.
* Calculation follow the spec: https://nomicon.io/Economics/README.html#validator-selection
* @params validators: current or next epoch validators.
* @params maxNumberOfSeats: maximum number of seats in the network.
* @params minimumStakeRatio: minimum stake ratio
* @params protocolVersion: version of the protocol from genesis config
*/ function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocolVersion) {
if (protocolVersion && protocolVersion < 49) return findSeatPriceForProtocolBefore49(validators, maxNumberOfSeats);
if (!minimumStakeRatio) {
const deprecate = depd_1.default("findSeatPrice(validators, maxNumberOfSeats)");
deprecate("`use `findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio)` instead");
minimumStakeRatio = [
1,
6250
]; // harcoded minimumStakeRation from 12/7/21
}
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
}
exports.findSeatPrice = findSeatPrice;
function findSeatPriceForProtocolBefore49(validators, numSeats) {
const stakes = validators.map((v)=>new bn_js_1.default(v.stake, 10)).sort((a, b)=>a.cmp(b));
const num = new bn_js_1.default(numSeats);
const stakesSum = stakes.reduce((a, b)=>a.add(b));
if (stakesSum.lt(num)) throw new Error("Stakes are below seats");
// assert stakesSum >= numSeats
let left = new bn_js_1.default(1), right = stakesSum.add(new bn_js_1.default(1));
while(!left.eq(right.sub(new bn_js_1.default(1)))){
const mid = left.add(right).div(new bn_js_1.default(2));
let found = false;
let currentSum = new bn_js_1.default(0);
for(let i = 0; i < stakes.length; ++i){
currentSum = currentSum.add(stakes[i].div(mid));
if (currentSum.gte(num)) {
left = mid;
found = true;
break;
}
}
if (!found) right = mid;
}
return left;
}
// nearcore reference: https://github.com/near/nearcore/blob/5a8ae263ec07930cd34d0dcf5bcee250c67c02aa/chain/epoch_manager/src/validator_selection.rs#L308;L315
function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio) {
if (minimumStakeRatio.length != 2) throw Error("minimumStakeRatio should have 2 elements");
const stakes = validators.map((v)=>new bn_js_1.default(v.stake, 10)).sort((a, b)=>a.cmp(b));
const stakesSum = stakes.reduce((a, b)=>a.add(b));
if (validators.length < maxNumberOfSeats) return stakesSum.mul(new bn_js_1.default(minimumStakeRatio[0])).div(new bn_js_1.default(minimumStakeRatio[1]));
else return stakes[0].add(new bn_js_1.default(1));
}
/** Diff validators between current and next epoch.
* Returns additions, subtractions and changes to validator set.
* @params currentValidators: list of current validators.
* @params nextValidators: list of next validators.
*/ function diffEpochValidators(currentValidators, nextValidators) {
const validatorsMap = new Map();
currentValidators.forEach((v)=>validatorsMap.set(v.account_id, v));
const nextValidatorsSet = new Set(nextValidators.map((v)=>v.account_id));
return {
newValidators: nextValidators.filter((v)=>!validatorsMap.has(v.account_id)),
removedValidators: currentValidators.filter((v)=>!nextValidatorsSet.has(v.account_id)),
changedValidators: nextValidators.filter((v)=>validatorsMap.has(v.account_id) && validatorsMap.get(v.account_id).stake != v.stake).map((v)=>({
current: validatorsMap.get(v.account_id),
next: v
}))
};
}
exports.diffEpochValidators = diffEpochValidators;
},{"bn.js":"9pdNn","depd":"2jGeI"}],"hxSQV":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Account = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const depd_1 = __importDefault(require("depd"));
const transaction_1 = require("./transaction");
const providers_1 = require("./providers");
const borsh_1 = require("borsh");
const key_pair_1 = require("./utils/key_pair");
const errors_1 = require("./utils/errors");
const rpc_errors_1 = require("./utils/rpc_errors");
const constants_1 = require("./constants");
const exponential_backoff_1 = __importDefault(require("./utils/exponential-backoff"));
// Default number of retries with different nonce before giving up on a transaction.
const TX_NONCE_RETRY_NUMBER = 12;
// Default wait until next retry in millis.
const TX_NONCE_RETRY_WAIT = 500;
// Exponential back off for waiting to retry.
const TX_NONCE_RETRY_WAIT_BACKOFF = 1.5;
function parseJsonFromRawResponse(response) {
return JSON.parse(Buffer.from(response).toString());
}
function bytesJsonStringify(input) {
return Buffer.from(JSON.stringify(input));
}
/**
* This class provides common account related RPC calls including signing transactions with a {@link KeyPair}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
* @hint Use {@link WalletConnection} in the browser to redirect to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for Account/key management using the {@link BrowserLocalStorageKeyStore}.
* @see {@link https://nomicon.io/DataStructures/Account.html | Account Spec}
*/ class Account {
constructor(connection, accountId){
/** @hidden */ this.accessKeyByPublicKeyCache = {};
this.connection = connection;
this.accountId = accountId;
}
/** @hidden */ get ready() {
const deprecate = depd_1.default("Account.ready()");
deprecate("not needed anymore, always ready");
return Promise.resolve();
}
async fetchState() {
const deprecate = depd_1.default("Account.fetchState()");
deprecate("use `Account.state()` instead");
}
/**
* Returns basic NEAR account information via the `view_account` RPC query method
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-account}
*/ async state() {
return this.connection.provider.query({
request_type: "view_account",
account_id: this.accountId,
finality: "optimistic"
});
}
/** @hidden */ printLogsAndFailures(contractId, results) {
for (const result of results){
console.log(`Receipt${result.receiptIds.length > 1 ? "s" : ""}: ${result.receiptIds.join(", ")}`);
this.printLogs(contractId, result.logs, " ");
if (result.failure) console.warn(`\tFailure [${contractId}]: ${result.failure}`);
}
}
/** @hidden */ printLogs(contractId, logs, prefix = "") {
for (const log of logs)console.log(`${prefix}Log [${contractId}]: ${log}`);
}
/**
* Create a signed transaction which can be broadcast to the network
* @param receiverId NEAR account receiving the transaction
* @param actions list of actions to perform as part of the transaction
* @see {@link JsonRpcProvider.sendTransaction}
*/ async signTransaction(receiverId, actions) {
const accessKeyInfo = await this.findAccessKey(receiverId, actions);
if (!accessKeyInfo) throw new providers_1.TypedError(`Can not sign transactions for account ${this.accountId} on network ${this.connection.networkId}, no matching key pair found in ${this.connection.signer}.`, "KeyNotFound");
const { accessKey } = accessKeyInfo;
const block = await this.connection.provider.block({
finality: "final"
});
const blockHash = block.header.hash;
const nonce = ++accessKey.nonce;
return await transaction_1.signTransaction(receiverId, nonce, actions, borsh_1.baseDecode(blockHash), this.connection.signer, this.accountId, this.connection.networkId);
}
signAndSendTransaction(...args) {
if (typeof args[0] === "string") return this.signAndSendTransactionV1(args[0], args[1]);
else return this.signAndSendTransactionV2(args[0]);
}
signAndSendTransactionV1(receiverId, actions) {
const deprecate = depd_1.default("Account.signAndSendTransaction(receiverId, actions");
deprecate("use `Account.signAndSendTransaction(SignAndSendTransactionOptions)` instead");
return this.signAndSendTransactionV2({
receiverId,
actions
});
}
async signAndSendTransactionV2({ receiverId , actions , returnError }) {
let txHash, signedTx;
// TODO: TX_NONCE (different constants for different uses of exponentialBackoff?)
const result = await exponential_backoff_1.default(TX_NONCE_RETRY_WAIT, TX_NONCE_RETRY_NUMBER, TX_NONCE_RETRY_WAIT_BACKOFF, async ()=>{
[txHash, signedTx] = await this.signTransaction(receiverId, actions);
const publicKey = signedTx.transaction.publicKey;
try {
return await this.connection.provider.sendTransaction(signedTx);
} catch (error) {
if (error.type === "InvalidNonce") {
errors_1.logWarning(`Retrying transaction ${receiverId}:${borsh_1.baseEncode(txHash)} with new nonce.`);
delete this.accessKeyByPublicKeyCache[publicKey.toString()];
return null;
}
if (error.type === "Expired") {
errors_1.logWarning(`Retrying transaction ${receiverId}:${borsh_1.baseEncode(txHash)} due to expired block hash`);
return null;
}
error.context = new providers_1.ErrorContext(borsh_1.baseEncode(txHash));
throw error;
}
});
if (!result) // TODO: This should have different code actually, as means "transaction not submitted for sure"
throw new providers_1.TypedError("nonce retries exceeded for transaction. This usually means there are too many parallel requests with the same access key.", "RetriesExceeded");
const flatLogs = [
result.transaction_outcome,
...result.receipts_outcome
].reduce((acc, it)=>{
if (it.outcome.logs.length || typeof it.outcome.status === "object" && typeof it.outcome.status.Failure === "object") return acc.concat({
"receiptIds": it.outcome.receipt_ids,
"logs": it.outcome.logs,
"failure": typeof it.outcome.status.Failure != "undefined" ? rpc_errors_1.parseRpcError(it.outcome.status.Failure) : null
});
else return acc;
}, []);
this.printLogsAndFailures(signedTx.transaction.receiverId, flatLogs);
if (!returnError && typeof result.status === "object" && typeof result.status.Failure === "object") {
// if error data has error_message and error_type properties, we consider that node returned an error in the old format
if (result.status.Failure.error_message && result.status.Failure.error_type) throw new providers_1.TypedError(`Transaction ${result.transaction_outcome.id} failed. ${result.status.Failure.error_message}`, result.status.Failure.error_type);
else throw rpc_errors_1.parseResultError(result);
}
// TODO: if Tx is Unknown or Started.
return result;
}
/**
* Finds the {@link AccessKeyView} associated with the accounts {@link PublicKey} stored in the {@link KeyStore}.
*
* @todo Find matching access key based on transaction (i.e. receiverId and actions)
*
* @param receiverId currently unused (see todo)
* @param actions currently unused (see todo)
* @returns `{ publicKey PublicKey; accessKey: AccessKeyView }`
*/ async findAccessKey(receiverId, actions) {
// TODO: Find matching access key based on transaction (i.e. receiverId and actions)
const publicKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
if (!publicKey) return null;
const cachedAccessKey = this.accessKeyByPublicKeyCache[publicKey.toString()];
if (cachedAccessKey !== undefined) return {
publicKey,
accessKey: cachedAccessKey
};
try {
const accessKey = await this.connection.provider.query({
request_type: "view_access_key",
account_id: this.accountId,
public_key: publicKey.toString(),
finality: "optimistic"
});
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if (this.accessKeyByPublicKeyCache[publicKey.toString()]) return {
publicKey,
accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()]
};
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;
return {
publicKey,
accessKey
};
} catch (e) {
if (e.type == "AccessKeyDoesNotExist") return null;
throw e;
}
}
/**
* Create a new account and deploy a contract to it
*
* @param contractId NEAR account where the contract is deployed
* @param publicKey The public key to add to the created contract account
* @param data The compiled contract code
* @param amount of NEAR to transfer to the created contract account. Transfer enough to pay for storage https://docs.near.org/docs/concepts/storage-staking
*/ async createAndDeployContract(contractId, publicKey, data, amount) {
const accessKey = transaction_1.fullAccessKey();
await this.signAndSendTransaction({
receiverId: contractId,
actions: [
transaction_1.createAccount(),
transaction_1.transfer(amount),
transaction_1.addKey(key_pair_1.PublicKey.from(publicKey), accessKey),
transaction_1.deployContract(data)
]
});
const contractAccount = new Account(this.connection, contractId);
return contractAccount;
}
/**
* @param receiverId NEAR account receiving Ⓝ
* @param amount Amount to send in yoctoⓃ
*/ async sendMoney(receiverId, amount) {
return this.signAndSendTransaction({
receiverId,
actions: [
transaction_1.transfer(amount)
]
});
}
/**
* @param newAccountId NEAR account name to be created
* @param publicKey A public key created from the masterAccount
*/ async createAccount(newAccountId, publicKey, amount) {
const accessKey = transaction_1.fullAccessKey();
return this.signAndSendTransaction({
receiverId: newAccountId,
actions: [
transaction_1.createAccount(),
transaction_1.transfer(amount),
transaction_1.addKey(key_pair_1.PublicKey.from(publicKey), accessKey)
]
});
}
/**
* @param beneficiaryId The NEAR account that will receive the remaining Ⓝ balance from the account being deleted
*/ async deleteAccount(beneficiaryId) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.deleteAccount(beneficiaryId)
]
});
}
/**
* @param data The compiled contract code
*/ async deployContract(data) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.deployContract(data)
]
});
}
async functionCall(...args) {
if (typeof args[0] === "string") return this.functionCallV1(args[0], args[1], args[2], args[3], args[4]);
else return this.functionCallV2(args[0]);
}
functionCallV1(contractId, methodName, args, gas, amount) {
const deprecate = depd_1.default("Account.functionCall(contractId, methodName, args, gas, amount)");
deprecate("use `Account.functionCall(FunctionCallOptions)` instead");
args = args || {};
this.validateArgs(args);
return this.signAndSendTransaction({
receiverId: contractId,
actions: [
transaction_1.functionCall(methodName, args, gas || constants_1.DEFAULT_FUNCTION_CALL_GAS, amount)
]
});
}
functionCallV2({ contractId , methodName , args ={} , gas =constants_1.DEFAULT_FUNCTION_CALL_GAS , attachedDeposit , walletMeta , walletCallbackUrl , stringify }) {
this.validateArgs(args);
const stringifyArg = stringify === undefined ? transaction_1.stringifyJsonOrBytes : stringify;
return this.signAndSendTransaction({
receiverId: contractId,
actions: [
transaction_1.functionCall(methodName, args, gas, attachedDeposit, stringifyArg)
],
walletMeta,
walletCallbackUrl
});
}
/**
* @see {@link https://docs.near.org/docs/concepts/account#access-keys}
* @todo expand this API to support more options.
* @param publicKey A public key to be associated with the contract
* @param contractId NEAR account where the contract is deployed
* @param methodNames The method names on the contract that should be allowed to be called. Pass null for no method names and '' or [] for any method names.
* @param amount Payment in yoctoⓃ that is sent to the contract during this function call
*/ async addKey(publicKey, contractId, methodNames, amount) {
if (!methodNames) methodNames = [];
if (!Array.isArray(methodNames)) methodNames = [
methodNames
];
let accessKey;
if (!contractId) accessKey = transaction_1.fullAccessKey();
else accessKey = transaction_1.functionCallAccessKey(contractId, methodNames, amount);
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.addKey(key_pair_1.PublicKey.from(publicKey), accessKey)
]
});
}
/**
* @param publicKey The public key to be deleted
* @returns {Promise<FinalExecutionOutcome>}
*/ async deleteKey(publicKey) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.deleteKey(key_pair_1.PublicKey.from(publicKey))
]
});
}
/**
* @see {@link https://docs.near.org/docs/validator/staking-overview}
*
* @param publicKey The public key for the account that's staking
* @param amount The account to stake in yoctoⓃ
*/ async stake(publicKey, amount) {
return this.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.stake(amount, key_pair_1.PublicKey.from(publicKey))
]
});
}
/** @hidden */ validateArgs(args) {
const isUint8Array = args.byteLength !== undefined && args.byteLength === args.length;
if (isUint8Array) return;
if (Array.isArray(args) || typeof args !== "object") throw new errors_1.PositionalArgsError();
}
/**
* Invoke a contract view function using the RPC API.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#call-a-contract-function}
*
* @param contractId NEAR account where the contract is deployed
* @param methodName The view-only method (no state mutations) name on the contract as it is written in the contract code
* @param args Any arguments to the view contract method, wrapped in JSON
* @param options.parse Parse the result of the call. Receives a Buffer (bytes array) and converts it to any object. By default result will be treated as json.
* @param options.stringify Convert input arguments into a bytes array. By default the input is treated as a JSON.
* @returns {Promise<any>}
*/ async viewFunction(contractId, methodName, args = {}, { parse =parseJsonFromRawResponse , stringify =bytesJsonStringify } = {}) {
this.validateArgs(args);
const serializedArgs = stringify(args).toString("base64");
const result = await this.connection.provider.query({
request_type: "call_function",
account_id: contractId,
method_name: methodName,
args_base64: serializedArgs,
finality: "optimistic"
});
if (result.logs) this.printLogs(contractId, result.logs);
return result.result && result.result.length > 0 && parse(Buffer.from(result.result));
}
/**
* Returns the state (key value pairs) of this account's contract based on the key prefix.
* Pass an empty string for prefix if you would like to return the entire state.
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-contract-state}
*
* @param prefix allows to filter which keys should be returned. Empty prefix means all keys. String prefix is utf-8 encoded.
* @param blockQuery specifies which block to query state at. By default returns last "optimistic" block (i.e. not necessarily finalized).
*/ async viewState(prefix, blockQuery = {
finality: "optimistic"
}) {
const { values } = await this.connection.provider.query({
request_type: "view_state",
...blockQuery,
account_id: this.accountId,
prefix_base64: Buffer.from(prefix).toString("base64")
});
return values.map(({ key , value })=>({
key: Buffer.from(key, "base64"),
value: Buffer.from(value, "base64")
}));
}
/**
* Get all access keys for the account
* @see {@link https://docs.near.org/docs/develop/front-end/rpc#view-access-key-list}
*/ async getAccessKeys() {
const response = await this.connection.provider.query({
request_type: "view_access_key_list",
account_id: this.accountId,
finality: "optimistic"
});
// A breaking API change introduced extra information into the
// response, so it now returns an object with a `keys` field instead
// of an array: https://github.com/nearprotocol/nearcore/pull/1789
if (Array.isArray(response)) return response;
return response.keys;
}
/**
* Returns a list of authorized apps
* @todo update the response value to return all the different keys, not just app keys.
*/ async getAccountDetails() {
// TODO: update the response value to return all the different keys, not just app keys.
// Also if we need this function, or getAccessKeys is good enough.
const accessKeys = await this.getAccessKeys();
const authorizedApps = accessKeys.filter((item)=>item.access_key.permission !== "FullAccess").map((item)=>{
const perm = item.access_key.permission;
return {
contractId: perm.FunctionCall.receiver_id,
amount: perm.FunctionCall.allowance,
publicKey: item.public_key
};
});
return {
authorizedApps
};
}
/**
* Returns calculated account balance
*/ async getAccountBalance() {
const protocolConfig = await this.connection.provider.experimental_protocolConfig({
finality: "final"
});
const state = await this.state();
const costPerByte = new bn_js_1.default(protocolConfig.runtime_config.storage_amount_per_byte);
const stateStaked = new bn_js_1.default(state.storage_usage).mul(costPerByte);
const staked = new bn_js_1.default(state.locked);
const totalBalance = new bn_js_1.default(state.amount).add(staked);
const availableBalance = totalBalance.sub(bn_js_1.default.max(staked, stateStaked));
return {
total: totalBalance.toString(),
stateStaked: stateStaked.toString(),
staked: staked.toString(),
available: availableBalance.toString()
};
}
}
exports.Account = Account;
},{"buffer":"dvCeB","bn.js":"9pdNn","depd":"2jGeI","./transaction":"jJQ5a","./providers":"gtL2a","borsh":"4JCmN","./utils/key_pair":"kBQFP","./utils/errors":"btMYy","./utils/rpc_errors":"1TB1L","./constants":"lUNnG","./utils/exponential-backoff":"51I5X"}],"lUNnG":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_FUNCTION_CALL_GAS = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
// Default amount of gas to be sent with the function calls. Used to pay for the fees
// incurred while running the contract execution. The unused amount will be refunded back to
// the originator.
// Due to protocol changes that charge upfront for the maximum possible gas price inflation due to
// full blocks, the price of max_prepaid_gas is decreased to `300 * 10**12`.
// For discussion see https://github.com/nearprotocol/NEPs/issues/67
exports.DEFAULT_FUNCTION_CALL_GAS = new bn_js_1.default("30000000000000");
},{"bn.js":"9pdNn"}],"7q1du":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Account2FA = exports.AccountMultisig = exports.MULTISIG_CONFIRM_METHODS = exports.MULTISIG_CHANGE_METHODS = exports.MULTISIG_DEPOSIT = exports.MULTISIG_GAS = exports.MULTISIG_ALLOWANCE = exports.MULTISIG_STORAGE_KEY = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const depd_1 = __importDefault(require("depd"));
const account_1 = require("./account");
const format_1 = require("./utils/format");
const key_pair_1 = require("./utils/key_pair");
const transaction_1 = require("./transaction");
const web_1 = require("./utils/web");
exports.MULTISIG_STORAGE_KEY = "__multisigRequest";
exports.MULTISIG_ALLOWANCE = new bn_js_1.default(format_1.parseNearAmount("1"));
// TODO: Different gas value for different requests (can reduce gas usage dramatically)
exports.MULTISIG_GAS = new bn_js_1.default("100000000000000");
exports.MULTISIG_DEPOSIT = new bn_js_1.default("0");
exports.MULTISIG_CHANGE_METHODS = [
"add_request",
"add_request_and_confirm",
"delete_request",
"confirm"
];
exports.MULTISIG_CONFIRM_METHODS = [
"confirm"
];
// in memory request cache for node w/o localStorage
const storageFallback = {
[exports.MULTISIG_STORAGE_KEY]: null
};
class AccountMultisig extends account_1.Account {
constructor(connection, accountId, options){
super(connection, accountId);
this.storage = options.storage;
this.onAddRequestResult = options.onAddRequestResult;
}
async signAndSendTransactionWithAccount(receiverId, actions) {
return super.signAndSendTransaction({
receiverId,
actions
});
}
signAndSendTransaction(...args) {
if (typeof args[0] === "string") return this._signAndSendTransaction({
receiverId: args[0],
actions: args[1]
});
return this._signAndSendTransaction(args[0]);
}
async _signAndSendTransaction({ receiverId , actions }) {
const { accountId } = this;
const args = Buffer.from(JSON.stringify({
request: {
receiver_id: receiverId,
actions: convertActions(actions, accountId, receiverId)
}
}));
let result;
try {
result = await super.signAndSendTransaction({
receiverId: accountId,
actions: [
transaction_1.functionCall("add_request_and_confirm", args, exports.MULTISIG_GAS, exports.MULTISIG_DEPOSIT)
]
});
} catch (e) {
if (e.toString().includes("Account has too many active requests. Confirm or delete some")) {
await this.deleteUnconfirmedRequests();
return await this.signAndSendTransaction(receiverId, actions);
}
throw e;
}
// TODO: Are following even needed? Seems like it throws on error already
if (!result.status) throw new Error("Request failed");
const status = {
...result.status
};
if (!status.SuccessValue || typeof status.SuccessValue !== "string") throw new Error("Request failed");
this.setRequest({
accountId,
actions,
requestId: parseInt(Buffer.from(status.SuccessValue, "base64").toString("ascii"), 10)
});
if (this.onAddRequestResult) await this.onAddRequestResult(result);
// NOTE there is no await on purpose to avoid blocking for 2fa
this.deleteUnconfirmedRequests();
return result;
}
async deleteUnconfirmedRequests() {
// TODO: Delete in batch, don't delete unexpired
// TODO: Delete in batch, don't delete unexpired (can reduce gas usage dramatically)
const request_ids = await this.getRequestIds();
const { requestId } = this.getRequest();
for (const requestIdToDelete of request_ids){
if (requestIdToDelete == requestId) continue;
try {
await super.signAndSendTransaction({
receiverId: this.accountId,
actions: [
transaction_1.functionCall("delete_request", {
request_id: requestIdToDelete
}, exports.MULTISIG_GAS, exports.MULTISIG_DEPOSIT)
]
});
} catch (e) {
console.warn("Attempt to delete an earlier request before 15 minutes failed. Will try again.");
}
}
}
// helpers
async getRequestIds() {
// TODO: Read requests from state to allow filtering by expiration time
// TODO: https://github.com/near/core-contracts/blob/305d1db4f4f2cf5ce4c1ef3479f7544957381f11/multisig/src/lib.rs#L84
return this.viewFunction(this.accountId, "list_request_ids");
}
getRequest() {
if (this.storage) return JSON.parse(this.storage.getItem(exports.MULTISIG_STORAGE_KEY) || "{}");
return storageFallback[exports.MULTISIG_STORAGE_KEY];
}
setRequest(data) {
if (this.storage) return this.storage.setItem(exports.MULTISIG_STORAGE_KEY, JSON.stringify(data));
storageFallback[exports.MULTISIG_STORAGE_KEY] = data;
}
}
exports.AccountMultisig = AccountMultisig;
class Account2FA extends AccountMultisig {
constructor(connection, accountId, options){
super(connection, accountId, options);
this.helperUrl = "https://helper.testnet.near.org";
this.helperUrl = options.helperUrl || this.helperUrl;
this.storage = options.storage;
this.sendCode = options.sendCode || this.sendCodeDefault;
this.getCode = options.getCode || this.getCodeDefault;
this.verifyCode = options.verifyCode || this.verifyCodeDefault;
this.onConfirmResult = options.onConfirmResult;
}
async signAndSendTransaction(...args) {
if (typeof args[0] === "string") {
const deprecate = depd_1.default("Account.signAndSendTransaction(receiverId, actions");
deprecate("use `Account2FA.signAndSendTransaction(SignAndSendTransactionOptions)` instead");
return this.__signAndSendTransaction({
receiverId: args[0],
actions: args[1]
});
} else return this.__signAndSendTransaction(args[0]);
}
async __signAndSendTransaction({ receiverId , actions }) {
await super.signAndSendTransaction({
receiverId,
actions
});
// TODO: Should following override onRequestResult in superclass instead of doing custom signAndSendTransaction?
await this.sendCode();
const result = await this.promptAndVerify();
if (this.onConfirmResult) await this.onConfirmResult(result);
return result;
}
// default helpers for CH deployments of multisig
async deployMultisig(contractBytes) {
const { accountId } = this;
const seedOrLedgerKey = (await this.getRecoveryMethods()).data.filter(({ kind , publicKey })=>(kind === "phrase" || kind === "ledger") && publicKey !== null).map((rm)=>rm.publicKey);
const fak2lak = (await this.getAccessKeys()).filter(({ public_key , access_key: { permission } })=>permission === "FullAccess" && !seedOrLedgerKey.includes(public_key)).map((ak)=>ak.public_key).map(toPK);
const confirmOnlyKey = toPK((await this.postSignedJson("/2fa/getAccessKey", {
accountId
})).publicKey);
const newArgs = Buffer.from(JSON.stringify({
"num_confirmations": 2
}));
const actions = [
...fak2lak.map((pk)=>transaction_1.deleteKey(pk)),
...fak2lak.map((pk)=>transaction_1.addKey(pk, transaction_1.functionCallAccessKey(accountId, exports.MULTISIG_CHANGE_METHODS, null))),
transaction_1.addKey(confirmOnlyKey, transaction_1.functionCallAccessKey(accountId, exports.MULTISIG_CONFIRM_METHODS, null)),
transaction_1.deployContract(contractBytes),
];
if ((await this.state()).code_hash === "11111111111111111111111111111111") actions.push(transaction_1.functionCall("new", newArgs, exports.MULTISIG_GAS, exports.MULTISIG_DEPOSIT));
console.log("deploying multisig contract for", accountId);
return await super.signAndSendTransactionWithAccount(accountId, actions);
}
async disable(contractBytes) {
const { accountId } = this;
const accessKeys = await this.getAccessKeys();
const lak2fak = accessKeys.filter(({ access_key })=>access_key.permission !== "FullAccess").filter(({ access_key })=>{
const perm = access_key.permission.FunctionCall;
return perm.receiver_id === accountId && perm.method_names.length === 4 && perm.method_names.includes("add_request_and_confirm");
});
const confirmOnlyKey = key_pair_1.PublicKey.from((await this.postSignedJson("/2fa/getAccessKey", {
accountId
})).publicKey);
const actions = [
transaction_1.deleteKey(confirmOnlyKey),
...lak2fak.map(({ public_key })=>transaction_1.deleteKey(key_pair_1.PublicKey.from(public_key))),
...lak2fak.map(({ public_key })=>transaction_1.addKey(key_pair_1.PublicKey.from(public_key), null)),
transaction_1.deployContract(contractBytes),
];
console.log("disabling 2fa for", accountId);
return await this.signAndSendTransaction({
receiverId: accountId,
actions
});
}
async sendCodeDefault() {
const { accountId } = this;
const { requestId } = this.getRequest();
const method = await this.get2faMethod();
await this.postSignedJson("/2fa/send", {
accountId,
method,
requestId
});
return requestId;
}
async getCodeDefault(method) {
throw new Error('There is no getCode callback provided. Please provide your own in AccountMultisig constructor options. It has a parameter method where method.kind is "email" or "phone".');
}
async promptAndVerify() {
const method = await this.get2faMethod();
const securityCode = await this.getCode(method);
try {
const result = await this.verifyCode(securityCode);
// TODO: Parse error from result for real (like in normal account.signAndSendTransaction)
return result;
} catch (e) {
console.warn("Error validating security code:", e);
if (e.toString().includes("invalid 2fa code provided") || e.toString().includes("2fa code not valid")) return await this.promptAndVerify();
throw e;
}
}
async verifyCodeDefault(securityCode) {
const { accountId } = this;
const request = this.getRequest();
if (!request) throw new Error("no request pending");
const { requestId } = request;
return await this.postSignedJson("/2fa/verify", {
accountId,
securityCode,
requestId
});
}
async getRecoveryMethods() {
const { accountId } = this;
return {
accountId,
data: await this.postSignedJson("/account/recoveryMethods", {
accountId
})
};
}
async get2faMethod() {
let { data } = await this.getRecoveryMethods();
if (data && data.length) data = data.find((m)=>m.kind.indexOf("2fa-") === 0);
if (!data) return null;
const { kind , detail } = data;
return {
kind,
detail
};
}
async signatureFor() {
const { accountId } = this;
const block = await this.connection.provider.block({
finality: "final"
});
const blockNumber = block.header.height.toString();
const signed = await this.connection.signer.signMessage(Buffer.from(blockNumber), accountId, this.connection.networkId);
const blockNumberSignature = Buffer.from(signed.signature).toString("base64");
return {
blockNumber,
blockNumberSignature
};
}
async postSignedJson(path, body) {
return await web_1.fetchJson(this.helperUrl + path, JSON.stringify({
...body,
...await this.signatureFor()
}));
}
}
exports.Account2FA = Account2FA;
// helpers
const toPK = (pk)=>key_pair_1.PublicKey.from(pk);
const convertPKForContract = (pk)=>pk.toString().replace("ed25519:", "");
const convertActions = (actions, accountId, receiverId)=>actions.map((a)=>{
const type = a.enum;
const { gas , publicKey , methodName , args , deposit , accessKey , code } = a[type];
const action = {
type: type[0].toUpperCase() + type.substr(1),
gas: gas && gas.toString() || undefined,
public_key: publicKey && convertPKForContract(publicKey) || undefined,
method_name: methodName,
args: args && Buffer.from(args).toString("base64") || undefined,
code: code && Buffer.from(code).toString("base64") || undefined,
amount: deposit && deposit.toString() || undefined,
deposit: deposit && deposit.toString() || "0",
permission: undefined
};
if (accessKey) {
if (receiverId === accountId && accessKey.permission.enum !== "fullAccess") action.permission = {
receiver_id: accountId,
allowance: exports.MULTISIG_ALLOWANCE.toString(),
method_names: exports.MULTISIG_CHANGE_METHODS
};
if (accessKey.permission.enum === "functionCall") {
const { receiverId: receiver_id , methodNames: method_names , allowance } = accessKey.permission.functionCall;
action.permission = {
receiver_id,
allowance: allowance && allowance.toString() || undefined,
method_names
};
}
}
return action;
});
},{"buffer":"dvCeB","bn.js":"9pdNn","depd":"2jGeI","./account":"hxSQV","./utils/format":"16c5X","./utils/key_pair":"kBQFP","./transaction":"jJQ5a","./utils/web":"iSqiB"}],"aQbxV":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UrlAccountCreator = exports.LocalAccountCreator = exports.AccountCreator = void 0;
const web_1 = require("./utils/web");
/**
* Account creator provides an interface for implementations to actually create accounts
*/ class AccountCreator {
}
exports.AccountCreator = AccountCreator;
class LocalAccountCreator extends AccountCreator {
constructor(masterAccount, initialBalance){
super();
this.masterAccount = masterAccount;
this.initialBalance = initialBalance;
}
/**
* Creates an account using a masterAccount, meaning the new account is created from an existing account
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/ async createAccount(newAccountId, publicKey) {
await this.masterAccount.createAccount(newAccountId, publicKey, this.initialBalance);
}
}
exports.LocalAccountCreator = LocalAccountCreator;
class UrlAccountCreator extends AccountCreator {
constructor(connection, helperUrl){
super();
this.connection = connection;
this.helperUrl = helperUrl;
}
/**
* Creates an account using a helperUrl
* This is [hosted here](https://helper.nearprotocol.com) or set up locally with the [near-contract-helper](https://github.com/nearprotocol/near-contract-helper) repository
* @param newAccountId The name of the NEAR account to be created
* @param publicKey The public key from the masterAccount used to create this account
* @returns {Promise<void>}
*/ async createAccount(newAccountId, publicKey) {
await web_1.fetchJson(`${this.helperUrl}/account`, JSON.stringify({
newAccountId,
newAccountPublicKey: publicKey.toString()
}));
}
}
exports.UrlAccountCreator = UrlAccountCreator;
},{"./utils/web":"iSqiB"}],"3ThJM":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Connection = void 0;
const providers_1 = require("./providers");
const signer_1 = require("./signer");
/**
* @param config Contains connection info details
* @returns {Provider}
*/ function getProvider(config) {
switch(config.type){
case undefined:
return config;
case "JsonRpcProvider":
return new providers_1.JsonRpcProvider({
...config.args
});
default:
throw new Error(`Unknown provider type ${config.type}`);
}
}
/**
* @param config Contains connection info details
* @returns {Signer}
*/ function getSigner(config) {
switch(config.type){
case undefined:
return config;
case "InMemorySigner":
return new signer_1.InMemorySigner(config.keyStore);
default:
throw new Error(`Unknown signer type ${config.type}`);
}
}
/**
* Connects an account to a given network via a given provider
*/ class Connection {
constructor(networkId, provider, signer){
this.networkId = networkId;
this.provider = provider;
this.signer = signer;
}
/**
* @param config Contains connection info details
*/ static fromConfig(config) {
const provider = getProvider(config.provider);
const signer = getSigner(config.signer);
return new Connection(config.networkId, provider, signer);
}
}
exports.Connection = Connection;
},{"./providers":"gtL2a","./signer":"a6bzI"}],"a6bzI":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InMemorySigner = exports.Signer = void 0;
const js_sha256_1 = __importDefault(require("js-sha256"));
const key_pair_1 = require("./utils/key_pair");
const in_memory_key_store_1 = require("./key_stores/in_memory_key_store");
/**
* General signing interface, can be used for in memory signing, RPC singing, external wallet, HSM, etc.
*/ class Signer {
}
exports.Signer = Signer;
/**
* Signs using in memory key store.
*/ class InMemorySigner extends Signer {
constructor(keyStore){
super();
this.keyStore = keyStore;
}
/**
* Creates a single account Signer instance with account, network and keyPair provided.
*
* Intended to be useful for temporary keys (e.g. claiming a Linkdrop).
*
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @param accountId The NEAR account to assign the key pair to
* @param keyPair The keyPair to use for signing
*/ static async fromKeyPair(networkId, accountId, keyPair) {
const keyStore = new in_memory_key_store_1.InMemoryKeyStore();
await keyStore.setKey(networkId, accountId, keyPair);
return new InMemorySigner(keyStore);
}
/**
* Creates a public key for the account given
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns {Promise<PublicKey>}
*/ async createKey(accountId, networkId) {
const keyPair = key_pair_1.KeyPair.fromRandom("ed25519");
await this.keyStore.setKey(networkId, accountId, keyPair);
return keyPair.getPublicKey();
}
/**
* Gets the existing public key for a given account
* @param accountId The NEAR account to assign a public key to
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns {Promise<PublicKey>} Returns the public key or null if not found
*/ async getPublicKey(accountId, networkId) {
const keyPair = await this.keyStore.getKey(networkId, accountId);
if (keyPair === null) return null;
return keyPair.getPublicKey();
}
/**
* @param message A message to be signed, typically a serialized transaction
* @param accountId the NEAR account signing the message
* @param networkId The targeted network. (ex. default, betanet, etc…)
* @returns {Promise<Signature>}
*/ async signMessage(message, accountId, networkId) {
const hash = new Uint8Array(js_sha256_1.default.sha256.array(message));
if (!accountId) throw new Error("InMemorySigner requires provided account id");
const keyPair = await this.keyStore.getKey(networkId, accountId);
if (keyPair === null) throw new Error(`Key for ${accountId} not found in ${networkId}`);
return keyPair.sign(hash);
}
toString() {
return `InMemorySigner(${this.keyStore})`;
}
}
exports.InMemorySigner = InMemorySigner;
},{"js-sha256":"ahVaM","./utils/key_pair":"kBQFP","./key_stores/in_memory_key_store":"fTfs7"}],"guo0T":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Contract = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const depd_1 = __importDefault(require("depd"));
const providers_1 = require("./providers");
const errors_1 = require("./utils/errors");
// Makes `function.name` return given name
function nameFunction(name, body) {
return ({
[name] (...args) {
return body(...args);
}
})[name];
}
const isUint8Array = (x)=>x && x.byteLength !== undefined && x.byteLength === x.length;
const isObject = (x)=>Object.prototype.toString.call(x) === "[object Object]";
/**
* Defines a smart contract on NEAR including the change (mutable) and view (non-mutable) methods
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#contract}
* @example
* ```js
* import { Contract } from 'near-api-js';
*
* async function contractExample() {
* const methodOptions = {
* viewMethods: ['getMessageByAccountId'],
* changeMethods: ['addMessage']
* };
* const contract = new Contract(
* wallet.account(),
* 'contract-id.testnet',
* methodOptions
* );
*
* // use a contract view method
* const messages = await contract.getMessages({
* accountId: 'example-account.testnet'
* });
*
* // use a contract change method
* await contract.addMessage({
* meta: 'some info',
* callbackUrl: 'https://example.com/callback',
* args: { text: 'my message' },
* amount: 1
* })
* }
* ```
*/ class Contract {
/**
* @param account NEAR account to sign change method transactions
* @param contractId NEAR account id where the contract is deployed
* @param options NEAR smart contract methods that your application will use. These will be available as `contract.methodName`
*/ constructor(account, contractId, options){
this.account = account;
this.contractId = contractId;
const { viewMethods =[] , changeMethods =[] } = options;
viewMethods.forEach((methodName)=>{
Object.defineProperty(this, methodName, {
writable: false,
enumerable: true,
value: nameFunction(methodName, async (args = {}, options = {}, ...ignored)=>{
if (ignored.length || !(isObject(args) || isUint8Array(args)) || !isObject(options)) throw new errors_1.PositionalArgsError();
return this.account.viewFunction(this.contractId, methodName, args, options);
})
});
});
changeMethods.forEach((methodName)=>{
Object.defineProperty(this, methodName, {
writable: false,
enumerable: true,
value: nameFunction(methodName, async (...args)=>{
if (args.length && (args.length > 3 || !(isObject(args[0]) || isUint8Array(args[0])))) throw new errors_1.PositionalArgsError();
if (args.length > 1 || !(args[0] && args[0].args)) {
const deprecate = depd_1.default("contract.methodName(args, gas, amount)");
deprecate("use `contract.methodName({ args, gas?, amount?, callbackUrl?, meta? })` instead");
return this._changeMethod({
methodName,
args: args[0],
gas: args[1],
amount: args[2]
});
}
return this._changeMethod({
methodName,
...args[0]
});
})
});
});
}
async _changeMethod({ args , methodName , gas , amount , meta , callbackUrl }) {
validateBNLike({
gas,
amount
});
const rawResult = await this.account.functionCall({
contractId: this.contractId,
methodName,
args,
gas,
attachedDeposit: amount,
walletMeta: meta,
walletCallbackUrl: callbackUrl
});
return providers_1.getTransactionLastResult(rawResult);
}
}
exports.Contract = Contract;
/**
* Validation on arguments being a big number from bn.js
* Throws if an argument is not in BN format or otherwise invalid
* @param argMap
*/ function validateBNLike(argMap) {
const bnLike = "number, decimal string or BN";
for (const argName of Object.keys(argMap)){
const argValue = argMap[argName];
if (argValue && !bn_js_1.default.isBN(argValue) && isNaN(argValue)) throw new errors_1.ArgumentTypeError(argName, bnLike, argValue);
}
}
},{"bn.js":"9pdNn","depd":"2jGeI","./providers":"gtL2a","./utils/errors":"btMYy"}],"9Ying":[function(require,module,exports) {
"use strict";
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Near = void 0;
/**
* This module contains the main class developers will use to interact with NEAR.
* The {@link Near} class is used to interact with {@link Account | Accounts} through the {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}.
* It is configured via the {@link NearConfig}.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#account}
*
* @module near
*/ const bn_js_1 = __importDefault(require("bn.js"));
const account_1 = require("./account");
const connection_1 = require("./connection");
const contract_1 = require("./contract");
const account_creator_1 = require("./account_creator");
/**
* This is the main class developers should use to interact with NEAR.
* @example
* ```js
* const near = new Near(config);
* ```
*/ class Near {
constructor(config){
this.config = config;
this.connection = connection_1.Connection.fromConfig({
networkId: config.networkId,
provider: {
type: "JsonRpcProvider",
args: {
url: config.nodeUrl,
headers: config.headers
}
},
signer: config.signer || {
type: "InMemorySigner",
keyStore: config.keyStore || config.deps.keyStore
}
});
if (config.masterAccount) {
// TODO: figure out better way of specifiying initial balance.
// Hardcoded number below must be enough to pay the gas cost to dev-deploy with near-shell for multiple times
const initialBalance = config.initialBalance ? new bn_js_1.default(config.initialBalance) : new bn_js_1.default("500000000000000000000000000");
this.accountCreator = new account_creator_1.LocalAccountCreator(new account_1.Account(this.connection, config.masterAccount), initialBalance);
} else if (config.helperUrl) this.accountCreator = new account_creator_1.UrlAccountCreator(this.connection, config.helperUrl);
else this.accountCreator = null;
}
/**
* @param accountId near accountId used to interact with the network.
*/ async account(accountId) {
const account = new account_1.Account(this.connection, accountId);
return account;
}
/**
* Create an account using the {@link AccountCreator}. Either:
* * using a masterAccount with {@link LocalAccountCreator}
* * using the helperUrl with {@link UrlAccountCreator}
* @see {@link NearConfig.masterAccount} and {@link NearConfig.helperUrl}-
*
* @param accountId
* @param publicKey
*/ async createAccount(accountId, publicKey) {
if (!this.accountCreator) throw new Error("Must specify account creator, either via masterAccount or helperUrl configuration settings.");
await this.accountCreator.createAccount(accountId, publicKey);
return new account_1.Account(this.connection, accountId);
}
/**
* @deprecated Use {@link Contract} instead.
* @param contractId
* @param options
*/ async loadContract(contractId, options) {
const account = new account_1.Account(this.connection, options.sender);
return new contract_1.Contract(account, contractId, options);
}
/**
* @deprecated Use {@link Account.sendMoney} instead.
* @param amount
* @param originator
* @param receiver
*/ async sendTokens(amount, originator, receiver) {
console.warn("near.sendTokens is deprecated. Use `yourAccount.sendMoney` instead.");
const account = new account_1.Account(this.connection, originator);
const result = await account.sendMoney(receiver, amount);
return result.transaction_outcome.id;
}
}
exports.Near = Near;
},{"bn.js":"9pdNn","./account":"hxSQV","./connection":"3ThJM","./contract":"guo0T","./account_creator":"aQbxV"}],"dHM3Z":[function(require,module,exports) {
"use strict";
var Buffer = require("buffer").Buffer;
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ConnectedWalletAccount = exports.WalletAccount = exports.WalletConnection = void 0;
/**
* The classes in this module are used in conjunction with the {@link BrowserLocalStorageKeyStore}. This module exposes two classes:
* * {@link WalletConnection} which redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
* * {@link ConnectedWalletAccount} is an {@link Account} implementation that uses {@link WalletConnection} to get keys
*
* @module walletAccount
*/ const depd_1 = __importDefault(require("depd"));
const account_1 = require("./account");
const transaction_1 = require("./transaction");
const utils_1 = require("./utils");
const borsh_1 = require("borsh");
const borsh_2 = require("borsh");
const LOGIN_WALLET_URL_SUFFIX = "/login/";
const MULTISIG_HAS_METHOD = "add_request_and_confirm";
const LOCAL_STORAGE_KEY_SUFFIX = "_wallet_auth_key";
const PENDING_ACCESS_KEY_PREFIX = "pending_key"; // browser storage key for a pending access key (i.e. key has been generated but we are not sure it was added yet)
/**
* This class is used in conjunction with the {@link BrowserLocalStorageKeyStore}.
* It redirects users to {@link https://docs.near.org/docs/tools/near-wallet | NEAR Wallet} for key management.
*
* @example {@link https://docs.near.org/docs/develop/front-end/naj-quick-reference#wallet}
* @example
* ```js
* // create new WalletConnection instance
* const wallet = new WalletConnection(near, 'my-app');
*
* // If not signed in redirect to the NEAR wallet to sign in
* // keys will be stored in the BrowserLocalStorageKeyStore
* if(!wallet.isSingnedIn()) return wallet.requestSignIn()
* ```
*/ class WalletConnection {
constructor(near, appKeyPrefix){
this._near = near;
const authDataKey = appKeyPrefix + LOCAL_STORAGE_KEY_SUFFIX;
const authData = JSON.parse(window.localStorage.getItem(authDataKey));
this._networkId = near.config.networkId;
this._walletBaseUrl = near.config.walletUrl;
appKeyPrefix = appKeyPrefix || near.config.contractName || "default";
this._keyStore = near.connection.signer.keyStore;
this._authData = authData || {
allKeys: []
};
this._authDataKey = authDataKey;
if (!this.isSignedIn()) this._completeSignInWithAccessKey();
}
/**
* Returns true, if this WalletAccount is authorized with the wallet.
* @example
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.isSignedIn();
* ```
*/ isSignedIn() {
return !!this._authData.accountId;
}
/**
* Returns authorized Account ID.
* @example
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* wallet.getAccountId();
* ```
*/ getAccountId() {
return this._authData.accountId || "";
}
/**
* Redirects current page to the wallet authentication page.
* @param options An optional options object
* @param options.contractId The NEAR account where the contract is deployed
* @param options.successUrl URL to redirect upon success. Default: current url
* @param options.failureUrl URL to redirect upon failure. Default: current url
*
* @example
* ```js
* const wallet = new WalletConnection(near, 'my-app');
* // redirects to the NEAR Wallet
* wallet.requestSignIn({ contractId: 'account-with-deploy-contract.near' });
* ```
*/ async requestSignIn(contractIdOrOptions = {}, title, successUrl, failureUrl) {
let options;
if (typeof contractIdOrOptions === "string") {
const deprecate = depd_1.default("requestSignIn(contractId, title)");
deprecate("`title` ignored; use `requestSignIn({ contractId, methodNames, successUrl, failureUrl })` instead");
options = {
contractId: contractIdOrOptions,
successUrl,
failureUrl
};
} else options = contractIdOrOptions;
const currentUrl = new URL(window.location.href);
const newUrl = new URL(this._walletBaseUrl + LOGIN_WALLET_URL_SUFFIX);
newUrl.searchParams.set("success_url", options.successUrl || currentUrl.href);
newUrl.searchParams.set("failure_url", options.failureUrl || currentUrl.href);
if (options.contractId) {
/* Throws exception if contract account does not exist */ const contractAccount = await this._near.account(options.contractId);
await contractAccount.state();
newUrl.searchParams.set("contract_id", options.contractId);
const accessKey = utils_1.KeyPair.fromRandom("ed25519");
newUrl.searchParams.set("public_key", accessKey.getPublicKey().toString());
await this._keyStore.setKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + accessKey.getPublicKey(), accessKey);
}
if (options.methodNames) options.methodNames.forEach((methodName)=>{
newUrl.searchParams.append("methodNames", methodName);
});
window.location.assign(newUrl.toString());
}
async requestSignTransactions(...args) {
if (Array.isArray(args[0])) {
const deprecate = depd_1.default("WalletConnection.requestSignTransactions(transactions, callbackUrl, meta)");
deprecate("use `WalletConnection.requestSignTransactions(RequestSignTransactionsOptions)` instead");
return this._requestSignTransactions({
transactions: args[0],
callbackUrl: args[1],
meta: args[2]
});
}
return this._requestSignTransactions(args[0]);
}
async _requestSignTransactions({ transactions , meta , callbackUrl }) {
const currentUrl = new URL(window.location.href);
const newUrl = new URL("sign", this._walletBaseUrl);
newUrl.searchParams.set("transactions", transactions.map((transaction)=>borsh_2.serialize(transaction_1.SCHEMA, transaction)).map((serialized)=>Buffer.from(serialized).toString("base64")).join(","));
newUrl.searchParams.set("callbackUrl", callbackUrl || currentUrl.href);
if (meta) newUrl.searchParams.set("meta", meta);
window.location.assign(newUrl.toString());
}
/**
* @hidden
* Complete sign in for a given account id and public key. To be invoked by the app when getting a callback from the wallet.
*/ async _completeSignInWithAccessKey() {
const currentUrl = new URL(window.location.href);
const publicKey = currentUrl.searchParams.get("public_key") || "";
const allKeys = (currentUrl.searchParams.get("all_keys") || "").split(",");
const accountId = currentUrl.searchParams.get("account_id") || "";
// TODO: Handle errors during login
if (accountId) {
this._authData = {
accountId,
allKeys
};
window.localStorage.setItem(this._authDataKey, JSON.stringify(this._authData));
if (publicKey) await this._moveKeyFromTempToPermanent(accountId, publicKey);
}
currentUrl.searchParams.delete("public_key");
currentUrl.searchParams.delete("all_keys");
currentUrl.searchParams.delete("account_id");
currentUrl.searchParams.delete("meta");
currentUrl.searchParams.delete("transactionHashes");
window.history.replaceState({}, document.title, currentUrl.toString());
}
/**
* @hidden
* @param accountId The NEAR account owning the given public key
* @param publicKey The public key being set to the key store
*/ async _moveKeyFromTempToPermanent(accountId, publicKey) {
const keyPair = await this._keyStore.getKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + publicKey);
await this._keyStore.setKey(this._networkId, accountId, keyPair);
await this._keyStore.removeKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + publicKey);
}
/**
* Sign out from the current account
* @example
* walletAccount.signOut();
*/ signOut() {
this._authData = {};
window.localStorage.removeItem(this._authDataKey);
}
/**
* Returns the current connected wallet account
*/ account() {
if (!this._connectedAccount) this._connectedAccount = new ConnectedWalletAccount(this, this._near.connection, this._authData.accountId);
return this._connectedAccount;
}
}
exports.WalletConnection = WalletConnection;
exports.WalletAccount = WalletConnection;
/**
* {@link Account} implementation which redirects to wallet using {@link WalletConnection} when no local key is available.
*/ class ConnectedWalletAccount extends account_1.Account {
constructor(walletConnection, connection, accountId){
super(connection, accountId);
this.walletConnection = walletConnection;
}
// Overriding Account methods
/**
* Sign a transaction by redirecting to the NEAR Wallet
* @see {@link WalletConnection.requestSignTransactions}
*/ signAndSendTransaction(...args) {
if (typeof args[0] === "string") return this._signAndSendTransaction({
receiverId: args[0],
actions: args[1]
});
return this._signAndSendTransaction(args[0]);
}
async _signAndSendTransaction({ receiverId , actions , walletMeta , walletCallbackUrl =window.location.href }) {
const localKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
let accessKey = await this.accessKeyForTransaction(receiverId, actions, localKey);
if (!accessKey) throw new Error(`Cannot find matching key for transaction sent to ${receiverId}`);
if (localKey && localKey.toString() === accessKey.public_key) try {
return await super.signAndSendTransaction({
receiverId,
actions
});
} catch (e) {
if (e.type === "NotEnoughAllowance") accessKey = await this.accessKeyForTransaction(receiverId, actions);
else throw e;
}
const block = await this.connection.provider.block({
finality: "final"
});
const blockHash = borsh_1.baseDecode(block.header.hash);
const publicKey = utils_1.PublicKey.from(accessKey.public_key);
// TODO: Cache & listen for nonce updates for given access key
const nonce = accessKey.access_key.nonce + 1;
const transaction = transaction_1.createTransaction(this.accountId, publicKey, receiverId, nonce, actions, blockHash);
await this.walletConnection.requestSignTransactions({
transactions: [
transaction
],
meta: walletMeta,
callbackUrl: walletCallbackUrl
});
return new Promise((resolve, reject)=>{
setTimeout(()=>{
reject(new Error("Failed to redirect to sign transaction"));
}, 1000);
});
// TODO: Aggregate multiple transaction request with "debounce".
// TODO: Introduce TrasactionQueue which also can be used to watch for status?
}
/**
* Check if given access key allows the function call or method attempted in transaction
* @param accessKey Array of {access_key: AccessKey, public_key: PublicKey} items
* @param receiverId The NEAR account attempting to have access
* @param actions The action(s) needed to be checked for access
*/ async accessKeyMatchesTransaction(accessKey, receiverId, actions) {
const { access_key: { permission } } = accessKey;
if (permission === "FullAccess") return true;
if (permission.FunctionCall) {
const { receiver_id: allowedReceiverId , method_names: allowedMethods } = permission.FunctionCall;
/********************************
Accept multisig access keys and let wallets attempt to signAndSendTransaction
If an access key has itself as receiverId and method permission add_request_and_confirm, then it is being used in a wallet with multisig contract: https://github.com/near/core-contracts/blob/671c05f09abecabe7a7e58efe942550a35fc3292/multisig/src/lib.rs#L149-L153
********************************/ if (allowedReceiverId === this.accountId && allowedMethods.includes(MULTISIG_HAS_METHOD)) return true;
if (allowedReceiverId === receiverId) {
if (actions.length !== 1) return false;
const [{ functionCall }] = actions;
return functionCall && (!functionCall.deposit || functionCall.deposit.toString() === "0") && (allowedMethods.length === 0 || allowedMethods.includes(functionCall.methodName));
// TODO: Handle cases when allowance doesn't have enough to pay for gas
}
}
// TODO: Support other permissions than FunctionCall
return false;
}
/**
* Helper function returning the access key (if it exists) to the receiver that grants the designated permission
* @param receiverId The NEAR account seeking the access key for a transaction
* @param actions The action(s) sought to gain access to
* @param localKey A local public key provided to check for access
* @returns Promise<any>
*/ async accessKeyForTransaction(receiverId, actions, localKey) {
const accessKeys = await this.getAccessKeys();
if (localKey) {
const accessKey = accessKeys.find((key)=>key.public_key.toString() === localKey.toString());
if (accessKey && await this.accessKeyMatchesTransaction(accessKey, receiverId, actions)) return accessKey;
}
const walletKeys = this.walletConnection._authData.allKeys;
for (const accessKey1 of accessKeys){
if (walletKeys.indexOf(accessKey1.public_key) !== -1 && await this.accessKeyMatchesTransaction(accessKey1, receiverId, actions)) return accessKey1;
}
return null;
}
}
exports.ConnectedWalletAccount = ConnectedWalletAccount;
},{"buffer":"dvCeB","depd":"2jGeI","./account":"hxSQV","./transaction":"jJQ5a","./utils":"jOCMH","borsh":"4JCmN"}],"7yTE6":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.connect = void 0;
/**
* Connect to NEAR using the provided configuration.
*
* {@link ConnectConfig.networkId} and {@link ConnectConfig.nodeUrl} are required.
*
* To sign transactions you can also pass: {@link ConnectConfig.keyStore}
*
* Both are passed they are prioritize in that order.
*
* @see {@link ConnectConfig}
* @example
* ```js
* async function initNear() {
* const near = await connect({
* networkId: 'testnet',
* nodeUrl: 'https://rpc.testnet.near.org'
* })
* }
* ```
*
* @module browserConnect
*/ const near_1 = require("./near");
/**
* Initialize connection to Near network.
*/ async function connect(config) {
return new near_1.Near(config);
}
exports.connect = connect;
},{"./near":"9Ying"}],"2YFhR":[function(require,module,exports) {
module.exports = require("./lib");
},{"./lib":"hDD9L"}],"hDD9L":[function(require,module,exports) {
require("capability/es5");
var capability = require("capability");
var polyfill;
if (capability("Error.captureStackTrace")) polyfill = require("./v8");
else if (capability("Error.prototype.stack")) polyfill = require("./non-v8/index");
else polyfill = require("./unsupported");
module.exports = polyfill();
},{"capability/es5":"5bger","capability":"45xjX","./v8":"a0VmX","./non-v8/index":"dx0bf","./unsupported":"75e5c"}],"5bger":[function(require,module,exports) {
require(".").check("es5");
},{".":"45xjX"}],"45xjX":[function(require,module,exports) {
require("./lib/definitions");
module.exports = require("./lib");
},{"./lib/definitions":"k0u9C","./lib":"4EqFb"}],"k0u9C":[function(require,module,exports) {
var capability = require("."), define = capability.define, test = capability.test;
define("strict mode", function() {
return this === undefined;
});
define("arguments.callee.caller", function() {
try {
return function() {
return arguments.callee.caller;
}() === arguments.callee;
} catch (strictModeIsEnforced) {
return false;
}
});
define("es5", function() {
return test("Array.prototype.forEach") && test("Array.prototype.map") && test("Function.prototype.bind") && test("Object.create") && test("Object.defineProperties") && test("Object.defineProperty") && test("Object.prototype.hasOwnProperty");
});
define("Array.prototype.forEach", function() {
return Array.prototype.forEach;
});
define("Array.prototype.map", function() {
return Array.prototype.map;
});
define("Function.prototype.bind", function() {
return Function.prototype.bind;
});
define("Object.create", function() {
return Object.create;
});
define("Object.defineProperties", function() {
return Object.defineProperties;
});
define("Object.defineProperty", function() {
return Object.defineProperty;
});
define("Object.prototype.hasOwnProperty", function() {
return Object.prototype.hasOwnProperty;
});
define("Error.captureStackTrace", function() {
return Error.captureStackTrace;
});
define("Error.prototype.stack", function() {
try {
throw new Error();
} catch (e) {
return e.stack || e.stacktrace;
}
});
},{".":"4EqFb"}],"4EqFb":[function(require,module,exports) {
var CapabilityDetector = require("./CapabilityDetector");
var detector = new CapabilityDetector();
var capability = function(name) {
return detector.test(name);
};
capability.define = function(name, test) {
detector.define(name, test);
};
capability.check = function(name) {
detector.check(name);
};
capability.test = capability;
module.exports = capability;
},{"./CapabilityDetector":"csHRg"}],"csHRg":[function(require,module,exports) {
var CapabilityDetector = function() {
this.tests = {};
this.cache = {};
};
CapabilityDetector.prototype = {
constructor: CapabilityDetector,
define: function(name, test) {
if (typeof name != "string" || !(test instanceof Function)) throw new Error("Invalid capability definition.");
if (this.tests[name]) throw new Error('Duplicated capability definition by "' + name + '".');
this.tests[name] = test;
},
check: function(name) {
if (!this.test(name)) throw new Error('The current environment does not support "' + name + '", therefore we cannot continue.');
},
test: function(name) {
if (this.cache[name] !== undefined) return this.cache[name];
if (!this.tests[name]) throw new Error('Unknown capability with name "' + name + '".');
var test = this.tests[name];
this.cache[name] = !!test();
return this.cache[name];
}
};
module.exports = CapabilityDetector;
},{}],"a0VmX":[function(require,module,exports) {
var prepareStackTrace = require("./prepareStackTrace");
module.exports = function() {
Error.getStackTrace = function(throwable) {
return throwable.stack;
};
return {
prepareStackTrace: prepareStackTrace
};
};
},{"./prepareStackTrace":"85RZD"}],"85RZD":[function(require,module,exports) {
var prepareStackTrace = function(throwable, frames, warnings) {
var string = "";
string += throwable.name || "Error";
string += ": " + (throwable.message || "");
if (warnings instanceof Array) for(var warningIndex in warnings){
var warning = warnings[warningIndex];
string += "\n # " + warning;
}
for(var frameIndex in frames){
var frame = frames[frameIndex];
string += "\n at " + frame.toString();
}
return string;
};
module.exports = prepareStackTrace;
},{}],"dx0bf":[function(require,module,exports) {
var FrameStringSource = require("./FrameStringSource"), FrameStringParser = require("./FrameStringParser"), cache = require("u3").cache, prepareStackTrace = require("../prepareStackTrace");
module.exports = function() {
Error.captureStackTrace = function captureStackTrace(throwable, terminator) {
var warnings;
var frameShifts = [
captureStackTrace
];
if (terminator) // additional frames can come here if arguments.callee.caller is supported
// otherwise it is hard to identify the terminator
frameShifts.push(terminator);
var captured = FrameStringSource.getInstance().captureFrameStrings(frameShifts);
Object.defineProperties(throwable, {
stack: {
configurable: true,
get: cache(function() {
var frames = FrameStringParser.getInstance().getFrames(captured.frameStrings, captured.functionValues);
return (Error.prepareStackTrace || prepareStackTrace)(throwable, frames, warnings);
})
},
cachedStack: {
configurable: true,
writable: true,
enumerable: false,
value: true
}
});
};
Error.getStackTrace = function(throwable) {
if (throwable.cachedStack) return throwable.stack;
var frameStrings = FrameStringSource.getInstance().getFrameStrings(throwable), frames = [], warnings;
if (frameStrings) frames = FrameStringParser.getInstance().getFrames(frameStrings, []);
else warnings = [
"The stack is not readable by unthrown errors in this environment."
];
var stack = (Error.prepareStackTrace || prepareStackTrace)(throwable, frames, warnings);
if (frameStrings) try {
Object.defineProperties(throwable, {
stack: {
configurable: true,
writable: true,
enumerable: false,
value: stack
},
cachedStack: {
configurable: true,
writable: true,
enumerable: false,
value: true
}
});
} catch (nonConfigurableError) {}
return stack;
};
return {
prepareStackTrace: prepareStackTrace
};
};
},{"./FrameStringSource":"8enMo","./FrameStringParser":"kqj4M","u3":"dIyaj","../prepareStackTrace":"85RZD"}],"8enMo":[function(require,module,exports) {
var Class = require("o3").Class, abstractMethod = require("o3").abstractMethod, eachCombination = require("u3").eachCombination, cache = require("u3").cache, capability = require("capability");
var AbstractFrameStringSource = Class(Object, {
prototype: {
captureFrameStrings: function(frameShifts) {
var error = this.createError();
frameShifts.unshift(this.captureFrameStrings);
frameShifts.unshift(this.createError);
var capturedFrameStrings = this.getFrameStrings(error);
var frameStrings = capturedFrameStrings.slice(frameShifts.length), functionValues = [];
if (capability("arguments.callee.caller")) {
var capturedFunctionValues = [
this.createError,
this.captureFrameStrings
];
try {
var aCaller = arguments.callee;
while(aCaller = aCaller.caller)capturedFunctionValues.push(aCaller);
} catch (useStrictError) {}
functionValues = capturedFunctionValues.slice(frameShifts.length);
}
return {
frameStrings: frameStrings,
functionValues: functionValues
};
},
getFrameStrings: function(error) {
var message = error.message || "";
var name = error.name || "";
var stackString = this.getStackString(error);
if (stackString === undefined) return;
var stackStringChunks = stackString.split("\n");
var fromPosition = 0;
var toPosition = stackStringChunks.length;
if (this.hasHeader) fromPosition += name.split("\n").length + message.split("\n").length - 1;
if (this.hasFooter) toPosition -= 1;
return stackStringChunks.slice(fromPosition, toPosition);
},
createError: abstractMethod,
getStackString: abstractMethod,
hasHeader: undefined,
hasFooter: undefined
}
});
var FrameStringSourceCalibrator = Class(Object, {
prototype: {
calibrateClass: function(FrameStringSource) {
return this.calibrateMethods(FrameStringSource) && this.calibrateEnvelope(FrameStringSource);
},
calibrateMethods: function(FrameStringSource) {
try {
eachCombination([
[
function(message) {
return new Error(message);
},
function(message) {
try {
throw new Error(message);
} catch (error) {
return error;
}
}
],
[
function(error) {
return error.stack;
},
function(error) {
return error.stacktrace;
}
]
], function(createError, getStackString) {
if (getStackString(createError())) throw {
getStackString: getStackString,
createError: createError
};
});
} catch (workingImplementation) {
Class.merge.call(FrameStringSource, {
prototype: workingImplementation
});
return true;
}
return false;
},
calibrateEnvelope: function(FrameStringSource) {
var getStackString = FrameStringSource.prototype.getStackString;
var createError = FrameStringSource.prototype.createError;
var calibratorStackString = getStackString(createError("marker"));
var calibratorFrameStrings = calibratorStackString.split("\n");
Class.merge.call(FrameStringSource, {
prototype: {
hasHeader: /marker/.test(calibratorFrameStrings[0]),
hasFooter: calibratorFrameStrings[calibratorFrameStrings.length - 1] === ""
}
});
return true;
}
}
});
module.exports = {
getClass: cache(function() {
var FrameStringSource;
if (FrameStringSource) return FrameStringSource;
FrameStringSource = Class(AbstractFrameStringSource, {});
var calibrator = new FrameStringSourceCalibrator();
if (!calibrator.calibrateClass(FrameStringSource)) throw new Error("Cannot read Error.prototype.stack in this environment.");
return FrameStringSource;
}),
getInstance: cache(function() {
var FrameStringSource = this.getClass();
var instance = new FrameStringSource();
return instance;
})
};
},{"o3":"gP4B7","u3":"dIyaj","capability":"45xjX"}],"gP4B7":[function(require,module,exports) {
require("capability/es5");
module.exports = require("./lib");
},{"capability/es5":"5bger","./lib":"eoeZx"}],"eoeZx":[function(require,module,exports) {
module.exports = {
Class: require("./Class"),
abstractMethod: require("./abstractMethod")
};
},{"./Class":"k4Z0U","./abstractMethod":"d1LMy"}],"k4Z0U":[function(require,module,exports) {
var Class = function() {
var options = Object.create({
Source: Object,
config: {},
buildArgs: []
});
function checkOption(option) {
var key = "config";
if (option instanceof Function) key = "Source";
else if (option instanceof Array) key = "buildArgs";
else if (option instanceof Object) key = "config";
else throw new Error("Invalid configuration option.");
if (options.hasOwnProperty(key)) throw new Error("Duplicated configuration option: " + key + ".");
options[key] = option;
}
for(var index = 0, length = arguments.length; index < length; ++index)checkOption(arguments[index]);
var Source = options.Source, config = options.config, buildArgs = options.buildArgs;
return (Source.extend || Class.extend).call(Source, config, buildArgs);
};
Class.factory = function() {
var Source = this;
return function() {
var instance = this;
if (instance.build instanceof Function) instance.build.apply(instance, arguments);
if (instance.init instanceof Function) instance.init.apply(instance, arguments);
};
};
Class.extend = function(config, buildArgs) {
var Source = this;
if (!config) config = {};
var Subject;
if (config.prototype instanceof Object && config.prototype.constructor !== Object) Subject = config.prototype.constructor;
else if (config.factory instanceof Function) Subject = config.factory.call(Source);
Subject = (Source.clone || Class.clone).call(Source, Subject, buildArgs);
(Subject.merge || Class.merge).call(Subject, config);
return Subject;
};
Class.prototype.extend = function(config, buildArgs) {
var subject = this;
var instance = (subject.clone || Class.prototype.clone).apply(subject, buildArgs);
(instance.merge || Class.prototype.merge).call(instance, config);
return instance;
};
Class.clone = function(Subject, buildArgs) {
var Source = this;
if (!(Subject instanceof Function)) Subject = (Source.factory || Class.factory).call(Source);
Subject.prototype = (Source.prototype.clone || Class.prototype.clone).apply(Source.prototype, buildArgs || []);
Subject.prototype.constructor = Subject;
for(var staticProperty in Source)if (staticProperty !== "prototype") Subject[staticProperty] = Source[staticProperty];
return Subject;
};
Class.prototype.clone = function() {
var subject = this;
var instance = Object.create(subject);
if (instance.build instanceof Function) instance.build.apply(instance, arguments);
return instance;
};
Class.merge = function(config) {
var Subject = this;
for(var staticProperty in config)if (staticProperty !== "prototype") Subject[staticProperty] = config[staticProperty];
if (config.prototype instanceof Object) (Subject.prototype.merge || Class.prototype.merge).call(Subject.prototype, config.prototype);
return Subject;
};
Class.prototype.merge = function(config) {
var subject = this;
for(var property in config)if (property !== "constructor") subject[property] = config[property];
return subject;
};
Class.absorb = function(config) {
var Subject = this;
for(var staticProperty in config)if (staticProperty !== "prototype" && (Subject[staticProperty] === undefined || Subject[staticProperty] === Function.prototype[staticProperty])) Subject[staticProperty] = config[staticProperty];
if (config.prototype instanceof Object) (Subject.prototype.absorb || Class.prototype.absorb).call(Subject.prototype, config.prototype);
return Subject;
};
Class.prototype.absorb = function(config) {
var subject = this;
for(var property in config)if (property !== "constructor" && (subject[property] === undefined || subject[property] === Object.prototype[property])) subject[property] = config[property];
return subject;
};
Class.getAncestor = function() {
var Source = this;
if (Source !== Source.prototype.constructor) return Source.prototype.constructor;
};
Class.newInstance = function() {
var Subject = this;
var instance = Object.create(this.prototype);
Subject.apply(instance, arguments);
return instance;
};
module.exports = Class;
},{}],"d1LMy":[function(require,module,exports) {
module.exports = function() {
throw new Error("Not implemented.");
};
},{}],"dIyaj":[function(require,module,exports) {
module.exports = require("./lib");
},{"./lib":"9JH8M"}],"9JH8M":[function(require,module,exports) {
module.exports = {
cache: require("./cache"),
eachCombination: require("./eachCombination")
};
},{"./cache":"3mu2N","./eachCombination":"i1liH"}],"3mu2N":[function(require,module,exports) {
var cache = function(fn) {
var called = false, store;
if (!(fn instanceof Function)) {
called = true;
store = fn;
fn = null;
}
return function() {
if (!called) {
called = true;
store = fn.apply(this, arguments);
fn = null;
}
return store;
};
};
module.exports = cache;
},{}],"i1liH":[function(require,module,exports) {
module.exports = function eachCombination(alternativesByDimension, callback, combination) {
if (!combination) combination = [];
if (combination.length < alternativesByDimension.length) {
var alternatives = alternativesByDimension[combination.length];
for(var index in alternatives){
combination[combination.length] = alternatives[index];
eachCombination(alternativesByDimension, callback, combination);
--combination.length;
}
} else callback.apply(null, combination);
};
},{}],"kqj4M":[function(require,module,exports) {
var Class = require("o3").Class, Frame = require("./Frame"), cache = require("u3").cache;
var FrameStringParser = Class(Object, {
prototype: {
stackParser: null,
frameParser: null,
locationParsers: null,
constructor: function(options) {
Class.prototype.merge.call(this, options);
},
getFrames: function(frameStrings, functionValues) {
var frames = [];
for(var index = 0, length = frameStrings.length; index < length; ++index)frames[index] = this.getFrame(frameStrings[index], functionValues[index]);
return frames;
},
getFrame: function(frameString, functionValue) {
var config = {
frameString: frameString,
functionValue: functionValue
};
return new Frame(config);
}
}
});
module.exports = {
getClass: cache(function() {
return FrameStringParser;
}),
getInstance: cache(function() {
var FrameStringParser = this.getClass();
var instance = new FrameStringParser();
return instance;
})
};
},{"o3":"gP4B7","./Frame":"gHN0E","u3":"dIyaj"}],"gHN0E":[function(require,module,exports) {
var Class = require("o3").Class, abstractMethod = require("o3").abstractMethod;
var Frame = Class(Object, {
prototype: {
init: Class.prototype.merge,
frameString: undefined,
toString: function() {
return this.frameString;
},
functionValue: undefined,
getThis: abstractMethod,
getTypeName: abstractMethod,
getFunction: function() {
return this.functionValue;
},
getFunctionName: abstractMethod,
getMethodName: abstractMethod,
getFileName: abstractMethod,
getLineNumber: abstractMethod,
getColumnNumber: abstractMethod,
getEvalOrigin: abstractMethod,
isTopLevel: abstractMethod,
isEval: abstractMethod,
isNative: abstractMethod,
isConstructor: abstractMethod
}
});
module.exports = Frame;
},{"o3":"gP4B7"}],"75e5c":[function(require,module,exports) {
var cache = require("u3").cache, prepareStackTrace = require("./prepareStackTrace");
module.exports = function() {
Error.captureStackTrace = function(throwable, terminator) {
Object.defineProperties(throwable, {
stack: {
configurable: true,
get: cache(function() {
return (Error.prepareStackTrace || prepareStackTrace)(throwable, []);
})
},
cachedStack: {
configurable: true,
writable: true,
enumerable: false,
value: true
}
});
};
Error.getStackTrace = function(throwable) {
if (throwable.cachedStack) return throwable.stack;
var stack = (Error.prepareStackTrace || prepareStackTrace)(throwable, []);
try {
Object.defineProperties(throwable, {
stack: {
configurable: true,
writable: true,
enumerable: false,
value: stack
},
cachedStack: {
configurable: true,
writable: true,
enumerable: false,
value: true
}
});
} catch (nonConfigurableError) {}
return stack;
};
return {
prepareStackTrace: prepareStackTrace
};
};
},{"u3":"dIyaj","./prepareStackTrace":"85RZD"}],"1nDKo":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
parcelHelpers.export(exports, "setupModal", ()=>setupModal);
var _jsxRuntime = require("react/jsx-runtime");
var _client = require("react-dom/client");
var _react = require("react");
var global = arguments[3];
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var fails$f = function(exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
var fails$e = fails$f;
var functionBindNative = !fails$e(function() {
// eslint-disable-next-line es-x/no-function-prototype-bind -- safe
var test = (function() {}).bind();
// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test != "function" || test.hasOwnProperty("prototype");
});
var NATIVE_BIND$3 = functionBindNative;
var FunctionPrototype$2 = Function.prototype;
var bind$5 = FunctionPrototype$2.bind;
var call$e = FunctionPrototype$2.call;
var uncurryThis$g = NATIVE_BIND$3 && bind$5.bind(call$e, call$e);
var functionUncurryThis = NATIVE_BIND$3 ? function(fn) {
return fn && uncurryThis$g(fn);
} : function(fn) {
return fn && function() {
return call$e.apply(fn, arguments);
};
};
var uncurryThis$f = functionUncurryThis;
var toString$4 = uncurryThis$f({}.toString);
var stringSlice$1 = uncurryThis$f("".slice);
var classofRaw$1 = function(it) {
return stringSlice$1(toString$4(it), 8, -1);
};
var uncurryThis$e = functionUncurryThis;
var fails$d = fails$f;
var classof$5 = classofRaw$1;
var $Object$4 = Object;
var split = uncurryThis$e("".split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails$d(function() {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !$Object$4("z").propertyIsEnumerable(0);
}) ? function(it) {
return classof$5(it) == "String" ? split(it, "") : $Object$4(it);
} : $Object$4;
var $TypeError$d = TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible$2 = function(it) {
if (it == undefined) throw $TypeError$d("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var IndexedObject$2 = indexedObject;
var requireObjectCoercible$1 = requireObjectCoercible$2;
var toIndexedObject$5 = function(it) {
return IndexedObject$2(requireObjectCoercible$1(it));
};
var check = function(it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global$k = // eslint-disable-next-line es-x/no-global-this -- safe
check(typeof globalThis == "object" && globalThis) || check(typeof window == "object" && window) || // eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == "object" && self) || check(typeof commonjsGlobal == "object" && commonjsGlobal) || // eslint-disable-next-line no-new-func -- fallback
function() {
return this;
}() || Function("return this")();
var shared$3 = {
exports: {}
};
var global$j = global$k;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
var defineProperty$6 = Object.defineProperty;
var defineGlobalProperty$3 = function(key, value) {
try {
defineProperty$6(global$j, key, {
value: value,
configurable: true,
writable: true
});
} catch (error) {
global$j[key] = value;
}
return value;
};
var global$i = global$k;
var defineGlobalProperty$2 = defineGlobalProperty$3;
var SHARED = "__core-js_shared__";
var store$3 = global$i[SHARED] || defineGlobalProperty$2(SHARED, {});
var sharedStore = store$3;
var store$2 = sharedStore;
(shared$3.exports = function(key, value) {
return store$2[key] || (store$2[key] = value !== undefined ? value : {});
})("versions", []).push({
version: "3.23.3",
mode: "global",
copyright: "\xa9 2014-2022 Denis Pushkarev (zloirock.ru)",
license: "https://github.com/zloirock/core-js/blob/v3.23.3/LICENSE",
source: "https://github.com/zloirock/core-js"
});
var requireObjectCoercible = requireObjectCoercible$2;
var $Object$3 = Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
var toObject$5 = function(argument) {
return $Object$3(requireObjectCoercible(argument));
};
var uncurryThis$d = functionUncurryThis;
var toObject$4 = toObject$5;
var hasOwnProperty = uncurryThis$d({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es-x/no-object-hasown -- safe
var hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject$4(it), key);
};
var uncurryThis$c = functionUncurryThis;
var id = 0;
var postfix = Math.random();
var toString$3 = uncurryThis$c(1.0.toString);
var uid$2 = function(key) {
return "Symbol(" + (key === undefined ? "" : key) + ")_" + toString$3(++id + postfix, 36);
};
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
var isCallable$l = function(argument) {
return typeof argument == "function";
};
var global$h = global$k;
var isCallable$k = isCallable$l;
var aFunction = function(argument) {
return isCallable$k(argument) ? argument : undefined;
};
var getBuiltIn$8 = function(namespace, method) {
return arguments.length < 2 ? aFunction(global$h[namespace]) : global$h[namespace] && global$h[namespace][method];
};
var getBuiltIn$7 = getBuiltIn$8;
var engineUserAgent = getBuiltIn$7("navigator", "userAgent") || "";
var global$g = global$k;
var userAgent$5 = engineUserAgent;
var process$3 = global$g.process;
var Deno$1 = global$g.Deno;
var versions = process$3 && process$3.versions || Deno$1 && Deno$1.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split(".");
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent$5) {
match = userAgent$5.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent$5.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
var engineV8Version = version;
/* eslint-disable es-x/no-symbol -- required for testing */ var V8_VERSION$1 = engineV8Version;
var fails$c = fails$f;
// eslint-disable-next-line es-x/no-object-getownpropertysymbols -- required for testing
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails$c(function() {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol) || !(Object(symbol) instanceof Symbol) || // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && V8_VERSION$1 && V8_VERSION$1 < 41;
});
/* eslint-disable es-x/no-symbol -- required for testing */ var NATIVE_SYMBOL$2 = nativeSymbol;
var useSymbolAsUid = NATIVE_SYMBOL$2 && !Symbol.sham && typeof Symbol.iterator == "symbol";
var global$f = global$k;
var shared$2 = shared$3.exports;
var hasOwn$a = hasOwnProperty_1;
var uid$1 = uid$2;
var NATIVE_SYMBOL$1 = nativeSymbol;
var USE_SYMBOL_AS_UID$1 = useSymbolAsUid;
var WellKnownSymbolsStore = shared$2("wks");
var Symbol$1 = global$f.Symbol;
var symbolFor = Symbol$1 && Symbol$1["for"];
var createWellKnownSymbol = USE_SYMBOL_AS_UID$1 ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid$1;
var wellKnownSymbol$e = function(name) {
if (!hasOwn$a(WellKnownSymbolsStore, name) || !(NATIVE_SYMBOL$1 || typeof WellKnownSymbolsStore[name] == "string")) {
var description = "Symbol." + name;
if (NATIVE_SYMBOL$1 && hasOwn$a(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name];
else if (USE_SYMBOL_AS_UID$1 && symbolFor) WellKnownSymbolsStore[name] = symbolFor(description);
else WellKnownSymbolsStore[name] = createWellKnownSymbol(description);
}
return WellKnownSymbolsStore[name];
};
var isCallable$j = isCallable$l;
var isObject$7 = function(it) {
return typeof it == "object" ? it !== null : isCallable$j(it);
};
var isObject$6 = isObject$7;
var $String$3 = String;
var $TypeError$c = TypeError;
// `Assert: Type(argument) is Object`
var anObject$a = function(argument) {
if (isObject$6(argument)) return argument;
throw $TypeError$c($String$3(argument) + " is not an object");
};
var objectDefineProperties = {};
var fails$b = fails$f;
// Detect IE8's incomplete defineProperty implementation
var descriptors = !fails$b(function() {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, {
get: function() {
return 7;
}
})[1] != 7;
});
var DESCRIPTORS$b = descriptors;
var fails$a = fails$f;
// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
var v8PrototypeDefineBug = DESCRIPTORS$b && fails$a(function() {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty(function() {}, "prototype", {
value: 42,
writable: false
}).prototype != 42;
});
var objectDefineProperty = {};
var global$e = global$k;
var isObject$5 = isObject$7;
var document$3 = global$e.document;
// typeof document.createElement is 'object' in old IE
var EXISTS$1 = isObject$5(document$3) && isObject$5(document$3.createElement);
var documentCreateElement$2 = function(it) {
return EXISTS$1 ? document$3.createElement(it) : {};
};
var DESCRIPTORS$a = descriptors;
var fails$9 = fails$f;
var createElement$1 = documentCreateElement$2;
// Thanks to IE8 for its funny defineProperty
var ie8DomDefine = !DESCRIPTORS$a && !fails$9(function() {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty(createElement$1("div"), "a", {
get: function() {
return 7;
}
}).a != 7;
});
var NATIVE_BIND$2 = functionBindNative;
var call$d = Function.prototype.call;
var functionCall = NATIVE_BIND$2 ? call$d.bind(call$d) : function() {
return call$d.apply(call$d, arguments);
};
var uncurryThis$b = functionUncurryThis;
var objectIsPrototypeOf = uncurryThis$b({}.isPrototypeOf);
var getBuiltIn$6 = getBuiltIn$8;
var isCallable$i = isCallable$l;
var isPrototypeOf$3 = objectIsPrototypeOf;
var USE_SYMBOL_AS_UID = useSymbolAsUid;
var $Object$2 = Object;
var isSymbol$2 = USE_SYMBOL_AS_UID ? function(it) {
return typeof it == "symbol";
} : function(it) {
var $Symbol = getBuiltIn$6("Symbol");
return isCallable$i($Symbol) && isPrototypeOf$3($Symbol.prototype, $Object$2(it));
};
var $String$2 = String;
var tryToString$5 = function(argument) {
try {
return $String$2(argument);
} catch (error) {
return "Object";
}
};
var isCallable$h = isCallable$l;
var tryToString$4 = tryToString$5;
var $TypeError$b = TypeError;
// `Assert: IsCallable(argument) is true`
var aCallable$9 = function(argument) {
if (isCallable$h(argument)) return argument;
throw $TypeError$b(tryToString$4(argument) + " is not a function");
};
var aCallable$8 = aCallable$9;
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
var getMethod$3 = function(V, P) {
var func = V[P];
return func == null ? undefined : aCallable$8(func);
};
var call$c = functionCall;
var isCallable$g = isCallable$l;
var isObject$4 = isObject$7;
var $TypeError$a = TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
var ordinaryToPrimitive$1 = function(input, pref) {
var fn, val;
if (pref === "string" && isCallable$g(fn = input.toString) && !isObject$4(val = call$c(fn, input))) return val;
if (isCallable$g(fn = input.valueOf) && !isObject$4(val = call$c(fn, input))) return val;
if (pref !== "string" && isCallable$g(fn = input.toString) && !isObject$4(val = call$c(fn, input))) return val;
throw $TypeError$a("Can't convert object to primitive value");
};
var call$b = functionCall;
var isObject$3 = isObject$7;
var isSymbol$1 = isSymbol$2;
var getMethod$2 = getMethod$3;
var ordinaryToPrimitive = ordinaryToPrimitive$1;
var wellKnownSymbol$d = wellKnownSymbol$e;
var $TypeError$9 = TypeError;
var TO_PRIMITIVE = wellKnownSymbol$d("toPrimitive");
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
var toPrimitive$1 = function(input, pref) {
if (!isObject$3(input) || isSymbol$1(input)) return input;
var exoticToPrim = getMethod$2(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = "default";
result = call$b(exoticToPrim, input, pref);
if (!isObject$3(result) || isSymbol$1(result)) return result;
throw $TypeError$9("Can't convert object to primitive value");
}
if (pref === undefined) pref = "number";
return ordinaryToPrimitive(input, pref);
};
var toPrimitive = toPrimitive$1;
var isSymbol = isSymbol$2;
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
var toPropertyKey$3 = function(argument) {
var key = toPrimitive(argument, "string");
return isSymbol(key) ? key : key + "";
};
var DESCRIPTORS$9 = descriptors;
var IE8_DOM_DEFINE$1 = ie8DomDefine;
var V8_PROTOTYPE_DEFINE_BUG$1 = v8PrototypeDefineBug;
var anObject$9 = anObject$a;
var toPropertyKey$2 = toPropertyKey$3;
var $TypeError$8 = TypeError;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
var ENUMERABLE = "enumerable";
var CONFIGURABLE$1 = "configurable";
var WRITABLE = "writable";
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
objectDefineProperty.f = DESCRIPTORS$9 ? V8_PROTOTYPE_DEFINE_BUG$1 ? function defineProperty(O, P, Attributes) {
anObject$9(O);
P = toPropertyKey$2(P);
anObject$9(Attributes);
if (typeof O === "function" && P === "prototype" && "value" in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
var current = $getOwnPropertyDescriptor$1(O, P);
if (current && current[WRITABLE]) {
O[P] = Attributes.value;
Attributes = {
configurable: CONFIGURABLE$1 in Attributes ? Attributes[CONFIGURABLE$1] : current[CONFIGURABLE$1],
enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
writable: false
};
}
}
return $defineProperty(O, P, Attributes);
} : $defineProperty : function defineProperty(O, P, Attributes) {
anObject$9(O);
P = toPropertyKey$2(P);
anObject$9(Attributes);
if (IE8_DOM_DEFINE$1) try {
return $defineProperty(O, P, Attributes);
} catch (error) {}
if ("get" in Attributes || "set" in Attributes) throw $TypeError$8("Accessors not supported");
if ("value" in Attributes) O[P] = Attributes.value;
return O;
};
var ceil = Math.ceil;
var floor$1 = Math.floor;
// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es-x/no-math-trunc -- safe
var mathTrunc = Math.trunc || function trunc(x) {
var n = +x;
return (n > 0 ? floor$1 : ceil)(n);
};
var trunc = mathTrunc;
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
var toIntegerOrInfinity$2 = function(argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- NaN check
return number !== number || number === 0 ? 0 : trunc(number);
};
var toIntegerOrInfinity$1 = toIntegerOrInfinity$2;
var max$1 = Math.max;
var min$1 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex$2 = function(index, length) {
var integer = toIntegerOrInfinity$1(index);
return integer < 0 ? max$1(integer + length, 0) : min$1(integer, length);
};
var toIntegerOrInfinity = toIntegerOrInfinity$2;
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
var toLength$1 = function(argument) {
return argument > 0 ? min(toIntegerOrInfinity(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var toLength = toLength$1;
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
var lengthOfArrayLike$5 = function(obj) {
return toLength(obj.length);
};
var toIndexedObject$4 = toIndexedObject$5;
var toAbsoluteIndex$1 = toAbsoluteIndex$2;
var lengthOfArrayLike$4 = lengthOfArrayLike$5;
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod$1 = function(IS_INCLUDES) {
return function($this, el, fromIndex) {
var O = toIndexedObject$4($this);
var length = lengthOfArrayLike$4(O);
var index = toAbsoluteIndex$1(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while(length > index){
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
}
else for(; length > index; index++){
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
}
return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod$1(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod$1(false)
};
var hiddenKeys$4 = {};
var uncurryThis$a = functionUncurryThis;
var hasOwn$9 = hasOwnProperty_1;
var toIndexedObject$3 = toIndexedObject$5;
var indexOf = arrayIncludes.indexOf;
var hiddenKeys$3 = hiddenKeys$4;
var push$1 = uncurryThis$a([].push);
var objectKeysInternal = function(object, names) {
var O = toIndexedObject$3(object);
var i = 0;
var result = [];
var key;
for(key in O)!hasOwn$9(hiddenKeys$3, key) && hasOwn$9(O, key) && push$1(result, key);
// Don't enum bug & hidden keys
while(names.length > i)if (hasOwn$9(O, key = names[i++])) ~indexOf(result, key) || push$1(result, key);
return result;
};
// IE8- don't enum bug keys
var enumBugKeys$3 = [
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf"
];
var internalObjectKeys$1 = objectKeysInternal;
var enumBugKeys$2 = enumBugKeys$3;
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es-x/no-object-keys -- safe
var objectKeys$2 = Object.keys || function keys(O) {
return internalObjectKeys$1(O, enumBugKeys$2);
};
var DESCRIPTORS$8 = descriptors;
var V8_PROTOTYPE_DEFINE_BUG = v8PrototypeDefineBug;
var definePropertyModule$5 = objectDefineProperty;
var anObject$8 = anObject$a;
var toIndexedObject$2 = toIndexedObject$5;
var objectKeys$1 = objectKeys$2;
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es-x/no-object-defineproperties -- safe
objectDefineProperties.f = DESCRIPTORS$8 && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
anObject$8(O);
var props = toIndexedObject$2(Properties);
var keys = objectKeys$1(Properties);
var length = keys.length;
var index = 0;
var key;
while(length > index)definePropertyModule$5.f(O, key = keys[index++], props[key]);
return O;
};
var getBuiltIn$5 = getBuiltIn$8;
var html$2 = getBuiltIn$5("document", "documentElement");
var shared$1 = shared$3.exports;
var uid = uid$2;
var keys = shared$1("keys");
var sharedKey$3 = function(key) {
return keys[key] || (keys[key] = uid(key));
};
/* global ActiveXObject -- old IE, WSH */ var anObject$7 = anObject$a;
var definePropertiesModule = objectDefineProperties;
var enumBugKeys$1 = enumBugKeys$3;
var hiddenKeys$2 = hiddenKeys$4;
var html$1 = html$2;
var documentCreateElement$1 = documentCreateElement$2;
var sharedKey$2 = sharedKey$3;
var GT = ">";
var LT = "<";
var PROTOTYPE = "prototype";
var SCRIPT = "script";
var IE_PROTO$1 = sharedKey$2("IE_PROTO");
var EmptyConstructor = function() {};
var scriptTag = function(content) {
return LT + SCRIPT + GT + content + LT + "/" + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function(activeXDocument) {
activeXDocument.write(scriptTag(""));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function() {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement$1("iframe");
var JS = "java" + SCRIPT + ":";
var iframeDocument;
iframe.style.display = "none";
html$1.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag("document.F=Object"));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function() {
try {
activeXDocument = new ActiveXObject("htmlfile");
} catch (error) {}
NullProtoObject = typeof document != "undefined" ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys$1.length;
while(length--)delete NullProtoObject[PROTOTYPE][enumBugKeys$1[length]];
return NullProtoObject();
};
hiddenKeys$2[IE_PROTO$1] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es-x/no-object-create -- safe
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject$7(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO$1] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
};
var wellKnownSymbol$c = wellKnownSymbol$e;
var create$1 = objectCreate;
var defineProperty$5 = objectDefineProperty.f;
var UNSCOPABLES = wellKnownSymbol$c("unscopables");
var ArrayPrototype$1 = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype$1[UNSCOPABLES] == undefined) defineProperty$5(ArrayPrototype$1, UNSCOPABLES, {
configurable: true,
value: create$1(null)
});
// add a key to Array.prototype[@@unscopables]
var addToUnscopables$1 = function(key) {
ArrayPrototype$1[UNSCOPABLES][key] = true;
};
var iterators = {};
var uncurryThis$9 = functionUncurryThis;
var isCallable$f = isCallable$l;
var store$1 = sharedStore;
var functionToString = uncurryThis$9(Function.toString);
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable$f(store$1.inspectSource)) store$1.inspectSource = function(it) {
return functionToString(it);
};
var inspectSource$4 = store$1.inspectSource;
var global$d = global$k;
var isCallable$e = isCallable$l;
var inspectSource$3 = inspectSource$4;
var WeakMap$1 = global$d.WeakMap;
var nativeWeakMap = isCallable$e(WeakMap$1) && /native code/.test(inspectSource$3(WeakMap$1));
var createPropertyDescriptor$4 = function(bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var DESCRIPTORS$7 = descriptors;
var definePropertyModule$4 = objectDefineProperty;
var createPropertyDescriptor$3 = createPropertyDescriptor$4;
var createNonEnumerableProperty$4 = DESCRIPTORS$7 ? function(object, key, value) {
return definePropertyModule$4.f(object, key, createPropertyDescriptor$3(1, value));
} : function(object, key, value) {
object[key] = value;
return object;
};
var NATIVE_WEAK_MAP = nativeWeakMap;
var global$c = global$k;
var uncurryThis$8 = functionUncurryThis;
var isObject$2 = isObject$7;
var createNonEnumerableProperty$3 = createNonEnumerableProperty$4;
var hasOwn$8 = hasOwnProperty_1;
var shared = sharedStore;
var sharedKey$1 = sharedKey$3;
var hiddenKeys$1 = hiddenKeys$4;
var OBJECT_ALREADY_INITIALIZED = "Object already initialized";
var TypeError$2 = global$c.TypeError;
var WeakMap = global$c.WeakMap;
var set$1, get, has;
var enforce = function(it) {
return has(it) ? get(it) : set$1(it, {});
};
var getterFor = function(TYPE) {
return function(it) {
var state;
if (!isObject$2(it) || (state = get(it)).type !== TYPE) throw TypeError$2("Incompatible receiver, " + TYPE + " required");
return state;
};
};
if (NATIVE_WEAK_MAP || shared.state) {
var store = shared.state || (shared.state = new WeakMap());
var wmget = uncurryThis$8(store.get);
var wmhas = uncurryThis$8(store.has);
var wmset = uncurryThis$8(store.set);
set$1 = function(it, metadata) {
if (wmhas(store, it)) throw new TypeError$2(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
wmset(store, it, metadata);
return metadata;
};
get = function(it) {
return wmget(store, it) || {};
};
has = function(it) {
return wmhas(store, it);
};
} else {
var STATE = sharedKey$1("state");
hiddenKeys$1[STATE] = true;
set$1 = function(it, metadata) {
if (hasOwn$8(it, STATE)) throw new TypeError$2(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty$3(it, STATE, metadata);
return metadata;
};
get = function(it) {
return hasOwn$8(it, STATE) ? it[STATE] : {};
};
has = function(it) {
return hasOwn$8(it, STATE);
};
}
var internalState = {
set: set$1,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
var objectGetOwnPropertyDescriptor = {};
var objectPropertyIsEnumerable = {};
var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$2 = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor$2 && !$propertyIsEnumerable.call({
1: 2
}, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor$2(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;
var DESCRIPTORS$6 = descriptors;
var call$a = functionCall;
var propertyIsEnumerableModule$1 = objectPropertyIsEnumerable;
var createPropertyDescriptor$2 = createPropertyDescriptor$4;
var toIndexedObject$1 = toIndexedObject$5;
var toPropertyKey$1 = toPropertyKey$3;
var hasOwn$7 = hasOwnProperty_1;
var IE8_DOM_DEFINE = ie8DomDefine;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
objectGetOwnPropertyDescriptor.f = DESCRIPTORS$6 ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject$1(O);
P = toPropertyKey$1(P);
if (IE8_DOM_DEFINE) try {
return $getOwnPropertyDescriptor(O, P);
} catch (error) {}
if (hasOwn$7(O, P)) return createPropertyDescriptor$2(!call$a(propertyIsEnumerableModule$1.f, O, P), O[P]);
};
var makeBuiltIn$2 = {
exports: {}
};
var DESCRIPTORS$5 = descriptors;
var hasOwn$6 = hasOwnProperty_1;
var FunctionPrototype$1 = Function.prototype;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS$5 && Object.getOwnPropertyDescriptor;
var EXISTS = hasOwn$6(FunctionPrototype$1, "name");
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() {}).name === "something";
var CONFIGURABLE = EXISTS && (!DESCRIPTORS$5 || DESCRIPTORS$5 && getDescriptor(FunctionPrototype$1, "name").configurable);
var functionName = {
EXISTS: EXISTS,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE
};
var fails$8 = fails$f;
var isCallable$d = isCallable$l;
var hasOwn$5 = hasOwnProperty_1;
var DESCRIPTORS$4 = descriptors;
var CONFIGURABLE_FUNCTION_NAME$1 = functionName.CONFIGURABLE;
var inspectSource$2 = inspectSource$4;
var InternalStateModule$2 = internalState;
var enforceInternalState = InternalStateModule$2.enforce;
var getInternalState$1 = InternalStateModule$2.get;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
var defineProperty$4 = Object.defineProperty;
var CONFIGURABLE_LENGTH = DESCRIPTORS$4 && !fails$8(function() {
return defineProperty$4(function() {}, "length", {
value: 8
}).length !== 8;
});
var TEMPLATE = String(String).split("String");
var makeBuiltIn$1 = makeBuiltIn$2.exports = function(value, name, options) {
if (String(name).slice(0, 7) === "Symbol(") name = "[" + String(name).replace(/^Symbol\(([^)]*)\)/, "$1") + "]";
if (options && options.getter) name = "get " + name;
if (options && options.setter) name = "set " + name;
if (!hasOwn$5(value, "name") || CONFIGURABLE_FUNCTION_NAME$1 && value.name !== name) {
if (DESCRIPTORS$4) defineProperty$4(value, "name", {
value: name,
configurable: true
});
else value.name = name;
}
if (CONFIGURABLE_LENGTH && options && hasOwn$5(options, "arity") && value.length !== options.arity) defineProperty$4(value, "length", {
value: options.arity
});
try {
if (options && hasOwn$5(options, "constructor") && options.constructor) {
if (DESCRIPTORS$4) defineProperty$4(value, "prototype", {
writable: false
});
} else if (value.prototype) value.prototype = undefined;
} catch (error) {}
var state = enforceInternalState(value);
if (!hasOwn$5(state, "source")) state.source = TEMPLATE.join(typeof name == "string" ? name : "");
return value;
};
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
// eslint-disable-next-line no-extend-native -- required
Function.prototype.toString = makeBuiltIn$1(function toString() {
return isCallable$d(this) && getInternalState$1(this).source || inspectSource$2(this);
}, "toString");
var isCallable$c = isCallable$l;
var definePropertyModule$3 = objectDefineProperty;
var makeBuiltIn = makeBuiltIn$2.exports;
var defineGlobalProperty$1 = defineGlobalProperty$3;
var defineBuiltIn$5 = function(O, key, value, options) {
if (!options) options = {};
var simple = options.enumerable;
var name = options.name !== undefined ? options.name : key;
if (isCallable$c(value)) makeBuiltIn(value, name, options);
if (options.global) {
if (simple) O[key] = value;
else defineGlobalProperty$1(key, value);
} else {
try {
if (!options.unsafe) delete O[key];
else if (O[key]) simple = true;
} catch (error) {}
if (simple) O[key] = value;
else definePropertyModule$3.f(O, key, {
value: value,
enumerable: false,
configurable: !options.nonConfigurable,
writable: !options.nonWritable
});
}
return O;
};
var objectGetOwnPropertyNames = {};
var internalObjectKeys = objectKeysInternal;
var enumBugKeys = enumBugKeys$3;
var hiddenKeys = enumBugKeys.concat("length", "prototype");
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es-x/no-object-getownpropertynames -- safe
objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
var objectGetOwnPropertySymbols = {};
// eslint-disable-next-line es-x/no-object-getownpropertysymbols -- safe
objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
var getBuiltIn$4 = getBuiltIn$8;
var uncurryThis$7 = functionUncurryThis;
var getOwnPropertyNamesModule = objectGetOwnPropertyNames;
var getOwnPropertySymbolsModule$1 = objectGetOwnPropertySymbols;
var anObject$6 = anObject$a;
var concat$1 = uncurryThis$7([].concat);
// all object keys, includes non-enumerable and symbols
var ownKeys$1 = getBuiltIn$4("Reflect", "ownKeys") || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject$6(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule$1.f;
return getOwnPropertySymbols ? concat$1(keys, getOwnPropertySymbols(it)) : keys;
};
var hasOwn$4 = hasOwnProperty_1;
var ownKeys = ownKeys$1;
var getOwnPropertyDescriptorModule = objectGetOwnPropertyDescriptor;
var definePropertyModule$2 = objectDefineProperty;
var copyConstructorProperties$2 = function(target, source, exceptions) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule$2.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for(var i = 0; i < keys.length; i++){
var key = keys[i];
if (!hasOwn$4(target, key) && !(exceptions && hasOwn$4(exceptions, key))) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var fails$7 = fails$f;
var isCallable$b = isCallable$l;
var replacement = /#|\.prototype\./;
var isForced$2 = function(feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true : value == NATIVE ? false : isCallable$b(detection) ? fails$7(detection) : !!detection;
};
var normalize = isForced$2.normalize = function(string) {
return String(string).replace(replacement, ".").toLowerCase();
};
var data = isForced$2.data = {};
var NATIVE = isForced$2.NATIVE = "N";
var POLYFILL = isForced$2.POLYFILL = "P";
var isForced_1 = isForced$2;
var global$b = global$k;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var createNonEnumerableProperty$2 = createNonEnumerableProperty$4;
var defineBuiltIn$4 = defineBuiltIn$5;
var defineGlobalProperty = defineGlobalProperty$3;
var copyConstructorProperties$1 = copyConstructorProperties$2;
var isForced$1 = isForced_1;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.dontCallGetSet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/ var _export = function(options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) target = global$b;
else if (STATIC) target = global$b[TARGET] || defineGlobalProperty(TARGET, {});
else target = (global$b[TARGET] || {}).prototype;
if (target) for(key in source){
sourceProperty = source[key];
if (options.dontCallGetSet) {
descriptor = getOwnPropertyDescriptor$1(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced$1(GLOBAL ? key : TARGET + (STATIC ? "." : "#") + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty == typeof targetProperty) continue;
copyConstructorProperties$1(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || targetProperty && targetProperty.sham) createNonEnumerableProperty$2(sourceProperty, "sham", true);
defineBuiltIn$4(target, key, sourceProperty, options);
}
};
var fails$6 = fails$f;
var correctPrototypeGetter = !fails$6(function() {
function F() {}
F.prototype.constructor = null;
// eslint-disable-next-line es-x/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
var hasOwn$3 = hasOwnProperty_1;
var isCallable$a = isCallable$l;
var toObject$3 = toObject$5;
var sharedKey = sharedKey$3;
var CORRECT_PROTOTYPE_GETTER = correctPrototypeGetter;
var IE_PROTO = sharedKey("IE_PROTO");
var $Object$1 = Object;
var ObjectPrototype = $Object$1.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
// eslint-disable-next-line es-x/no-object-getprototypeof -- safe
var objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object$1.getPrototypeOf : function(O) {
var object = toObject$3(O);
if (hasOwn$3(object, IE_PROTO)) return object[IE_PROTO];
var constructor = object.constructor;
if (isCallable$a(constructor) && object instanceof constructor) return constructor.prototype;
return object instanceof $Object$1 ? ObjectPrototype : null;
};
var fails$5 = fails$f;
var isCallable$9 = isCallable$l;
var getPrototypeOf$1 = objectGetPrototypeOf;
var defineBuiltIn$3 = defineBuiltIn$5;
var wellKnownSymbol$b = wellKnownSymbol$e;
var ITERATOR$5 = wellKnownSymbol$b("iterator");
var BUGGY_SAFARI_ITERATORS$1 = false;
// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype$2, PrototypeOfArrayIteratorPrototype, arrayIterator;
/* eslint-disable es-x/no-array-prototype-keys -- safe */ if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!("next" in arrayIterator)) BUGGY_SAFARI_ITERATORS$1 = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf$1(getPrototypeOf$1(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = IteratorPrototype$2 == undefined || fails$5(function() {
var test = {};
// FF44- legacy iterators case
return IteratorPrototype$2[ITERATOR$5].call(test) !== test;
});
if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype$2 = {};
// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if (!isCallable$9(IteratorPrototype$2[ITERATOR$5])) defineBuiltIn$3(IteratorPrototype$2, ITERATOR$5, function() {
return this;
});
var iteratorsCore = {
IteratorPrototype: IteratorPrototype$2,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1
};
var defineProperty$3 = objectDefineProperty.f;
var hasOwn$2 = hasOwnProperty_1;
var wellKnownSymbol$a = wellKnownSymbol$e;
var TO_STRING_TAG$3 = wellKnownSymbol$a("toStringTag");
var setToStringTag$3 = function(target, TAG, STATIC) {
if (target && !STATIC) target = target.prototype;
if (target && !hasOwn$2(target, TO_STRING_TAG$3)) defineProperty$3(target, TO_STRING_TAG$3, {
configurable: true,
value: TAG
});
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var create = objectCreate;
var createPropertyDescriptor$1 = createPropertyDescriptor$4;
var setToStringTag$2 = setToStringTag$3;
var Iterators$4 = iterators;
var returnThis$1 = function() {
return this;
};
var createIteratorConstructor$1 = function(IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
var TO_STRING_TAG = NAME + " Iterator";
IteratorConstructor.prototype = create(IteratorPrototype$1, {
next: createPropertyDescriptor$1(+!ENUMERABLE_NEXT, next)
});
setToStringTag$2(IteratorConstructor, TO_STRING_TAG, false);
Iterators$4[TO_STRING_TAG] = returnThis$1;
return IteratorConstructor;
};
var isCallable$8 = isCallable$l;
var $String$1 = String;
var $TypeError$7 = TypeError;
var aPossiblePrototype$1 = function(argument) {
if (typeof argument == "object" || isCallable$8(argument)) return argument;
throw $TypeError$7("Can't set " + $String$1(argument) + " as a prototype");
};
/* eslint-disable no-proto -- safe */ var uncurryThis$6 = functionUncurryThis;
var anObject$5 = anObject$a;
var aPossiblePrototype = aPossiblePrototype$1;
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es-x/no-object-setprototypeof -- safe
var objectSetPrototypeOf = Object.setPrototypeOf || ("__proto__" in {} ? function() {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
setter = uncurryThis$6(Object.getOwnPropertyDescriptor(Object.prototype, "__proto__").set);
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) {}
return function setPrototypeOf(O, proto) {
anObject$5(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var $$a = _export;
var call$9 = functionCall;
var FunctionName = functionName;
var isCallable$7 = isCallable$l;
var createIteratorConstructor = createIteratorConstructor$1;
var getPrototypeOf = objectGetPrototypeOf;
var setPrototypeOf$1 = objectSetPrototypeOf;
var setToStringTag$1 = setToStringTag$3;
var createNonEnumerableProperty$1 = createNonEnumerableProperty$4;
var defineBuiltIn$2 = defineBuiltIn$5;
var wellKnownSymbol$9 = wellKnownSymbol$e;
var Iterators$3 = iterators;
var IteratorsCore = iteratorsCore;
var PROPER_FUNCTION_NAME = FunctionName.PROPER;
var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR$4 = wellKnownSymbol$9("iterator");
var KEYS = "keys";
var VALUES = "values";
var ENTRIES = "entries";
var returnThis = function() {
return this;
};
var defineIterator$1 = function(Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function(KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch(KIND){
case KEYS:
return function keys() {
return new IteratorConstructor(this, KIND);
};
case VALUES:
return function values() {
return new IteratorConstructor(this, KIND);
};
case ENTRIES:
return function entries() {
return new IteratorConstructor(this, KIND);
};
}
return function() {
return new IteratorConstructor(this);
};
};
var TO_STRING_TAG = NAME + " Iterator";
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR$4] || IterablePrototype["@@iterator"] || DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == "Array" ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf$1) setPrototypeOf$1(CurrentIteratorPrototype, IteratorPrototype);
else if (!isCallable$7(CurrentIteratorPrototype[ITERATOR$4])) defineBuiltIn$2(CurrentIteratorPrototype, ITERATOR$4, returnThis);
}
// Set @@toStringTag to native iterators
setToStringTag$1(CurrentIteratorPrototype, TO_STRING_TAG, true);
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (PROPER_FUNCTION_NAME && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
if (CONFIGURABLE_FUNCTION_NAME) createNonEnumerableProperty$1(IterablePrototype, "name", VALUES);
else {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() {
return call$9(nativeIterator, this);
};
}
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) {
for(KEY in methods)if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) defineBuiltIn$2(IterablePrototype, KEY, methods[KEY]);
} else $$a({
target: NAME,
proto: true,
forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME
}, methods);
}
// define iterator
if (IterablePrototype[ITERATOR$4] !== defaultIterator) defineBuiltIn$2(IterablePrototype, ITERATOR$4, defaultIterator, {
name: DEFAULT
});
Iterators$3[NAME] = defaultIterator;
return methods;
};
var toIndexedObject = toIndexedObject$5;
var addToUnscopables = addToUnscopables$1;
var Iterators$2 = iterators;
var InternalStateModule$1 = internalState;
var defineProperty$2 = objectDefineProperty.f;
var defineIterator = defineIterator$1;
var DESCRIPTORS$3 = descriptors;
var ARRAY_ITERATOR = "Array Iterator";
var setInternalState$1 = InternalStateModule$1.set;
var getInternalState = InternalStateModule$1.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
var es_array_iterator = defineIterator(Array, "Array", function(iterated, kind) {
setInternalState$1(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated),
index: 0,
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function() {
var state = getInternalState(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return {
value: undefined,
done: true
};
}
if (kind == "keys") return {
value: index,
done: false
};
if (kind == "values") return {
value: target[index],
done: false
};
return {
value: [
index,
target[index]
],
done: false
};
}, "values");
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values = Iterators$2.Arguments = Iterators$2.Array;
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables("keys");
addToUnscopables("values");
addToUnscopables("entries");
// V8 ~ Chrome 45- bug
if (DESCRIPTORS$3 && values.name !== "values") try {
defineProperty$2(values, "name", {
value: "values"
});
} catch (error) {}
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
var domIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
// in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList`
var documentCreateElement = documentCreateElement$2;
var classList = documentCreateElement("span").classList;
var DOMTokenListPrototype$1 = classList && classList.constructor && classList.constructor.prototype;
var domTokenListPrototype = DOMTokenListPrototype$1 === Object.prototype ? undefined : DOMTokenListPrototype$1;
var global$a = global$k;
var DOMIterables = domIterables;
var DOMTokenListPrototype = domTokenListPrototype;
var ArrayIteratorMethods = es_array_iterator;
var createNonEnumerableProperty = createNonEnumerableProperty$4;
var wellKnownSymbol$8 = wellKnownSymbol$e;
var ITERATOR$3 = wellKnownSymbol$8("iterator");
var TO_STRING_TAG$2 = wellKnownSymbol$8("toStringTag");
var ArrayValues = ArrayIteratorMethods.values;
var handlePrototype = function(CollectionPrototype, COLLECTION_NAME) {
if (CollectionPrototype) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[ITERATOR$3] !== ArrayValues) try {
createNonEnumerableProperty(CollectionPrototype, ITERATOR$3, ArrayValues);
} catch (error) {
CollectionPrototype[ITERATOR$3] = ArrayValues;
}
if (!CollectionPrototype[TO_STRING_TAG$2]) createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG$2, COLLECTION_NAME);
if (DOMIterables[COLLECTION_NAME]) for(var METHOD_NAME in ArrayIteratorMethods){
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
} catch (error1) {
CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
}
}
}
};
for(var COLLECTION_NAME in DOMIterables)handlePrototype(global$a[COLLECTION_NAME] && global$a[COLLECTION_NAME].prototype, COLLECTION_NAME);
handlePrototype(DOMTokenListPrototype, "DOMTokenList");
var DESCRIPTORS$2 = descriptors;
var uncurryThis$5 = functionUncurryThis;
var call$8 = functionCall;
var fails$4 = fails$f;
var objectKeys = objectKeys$2;
var getOwnPropertySymbolsModule = objectGetOwnPropertySymbols;
var propertyIsEnumerableModule = objectPropertyIsEnumerable;
var toObject$2 = toObject$5;
var IndexedObject$1 = indexedObject;
// eslint-disable-next-line es-x/no-object-assign -- safe
var $assign = Object.assign;
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
var defineProperty$1 = Object.defineProperty;
var concat = uncurryThis$5([].concat);
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
var objectAssign = !$assign || fails$4(function() {
// should have correct order of operations (Edge bug)
if (DESCRIPTORS$2 && $assign({
b: 1
}, $assign(defineProperty$1({}, "a", {
enumerable: true,
get: function() {
defineProperty$1(this, "b", {
value: 3,
enumerable: false
});
}
}), {
b: 2
})).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line es-x/no-symbol -- safe
var symbol = Symbol();
var alphabet = "abcdefghijklmnopqrst";
A[symbol] = 7;
alphabet.split("").forEach(function(chr) {
B[chr] = chr;
});
return $assign({}, A)[symbol] != 7 || objectKeys($assign({}, B)).join("") != alphabet;
}) ? function assign(target, source) {
var T = toObject$2(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
var propertyIsEnumerable = propertyIsEnumerableModule.f;
while(argumentsLength > index){
var S = IndexedObject$1(arguments[index++]);
var keys = getOwnPropertySymbols ? concat(objectKeys(S), getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while(length > j){
key = keys[j++];
if (!DESCRIPTORS$2 || call$8(propertyIsEnumerable, S, key)) T[key] = S[key];
}
}
return T;
} : $assign;
var $$9 = _export;
var assign = objectAssign;
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es-x/no-object-assign -- required for testing
$$9({
target: "Object",
stat: true,
arity: 2,
forced: Object.assign !== assign
}, {
assign: assign
});
/******************************************************************************
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.
***************************************************************************** */ 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());
});
}
const CloseButton = ({ onClick })=>{
return (0, _jsxRuntime.jsx)("button", Object.assign({
onClick: onClick,
className: "close-button"
}, {
children: (0, _jsxRuntime.jsxs)("svg", Object.assign({
xmlns: "http://www.w3.org/2000/svg",
height: "24",
viewBox: "0 0 24 24",
width: "24",
fill: "#C1C1C1"
}, {
children: [
(0, _jsxRuntime.jsx)("path", {
d: "M0 0h24v24H0z",
fill: "none"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
})
]
}))
}));
};
const ModalHeader = ({ title , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header"
}, {
children: [
(0, _jsxRuntime.jsx)("h3", Object.assign({
className: "middleTitle"
}, {
children: title
})),
(0, _jsxRuntime.jsx)(CloseButton, {
onClick: onCloseModal
})
]
}));
};
const BackArrow = ({ onClick })=>{
return (0, _jsxRuntime.jsx)("button", Object.assign({
onClick: onClick,
className: "back-button"
}, {
children: (0, _jsxRuntime.jsx)("svg", Object.assign({
width: "8",
height: "14",
viewBox: "0 0 8 14",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: (0, _jsxRuntime.jsx)("path", {
d: "M7 13L1 7L7 1",
stroke: "#6494EE",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
}))
}));
};
const WalletNetworkChanged = ({ selector , onBack , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header-wrapper"
}, {
children: [
(0, _jsxRuntime.jsx)(BackArrow, {
onClick: onBack
}),
(0, _jsxRuntime.jsx)(ModalHeader, {
title: "You Must Change the Network",
onCloseModal: onCloseModal
})
]
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "switch-network-message-wrapper"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsxs)("p", {
children: [
"We've detected that you need to change your wallet's network to",
(0, _jsxRuntime.jsx)("strong", Object.assign({
className: "network-id"
}, {
children: ` ${selector.options.network.networkId}`
})),
" ",
"for this dApp."
]
}),
(0, _jsxRuntime.jsx)("p", {
children: "Some wallets may not support changing networks. If you can not change networks you may consider switching to another wallet."
})
]
}))
}))
]
});
};
var tryToString$3 = tryToString$5;
var $TypeError$6 = TypeError;
var deletePropertyOrThrow$1 = function(O, P) {
if (!delete O[P]) throw $TypeError$6("Cannot delete property " + tryToString$3(P) + " of " + tryToString$3(O));
};
var wellKnownSymbol$7 = wellKnownSymbol$e;
var TO_STRING_TAG$1 = wellKnownSymbol$7("toStringTag");
var test$1 = {};
test$1[TO_STRING_TAG$1] = "z";
var toStringTagSupport = String(test$1) === "[object z]";
var TO_STRING_TAG_SUPPORT = toStringTagSupport;
var isCallable$6 = isCallable$l;
var classofRaw = classofRaw$1;
var wellKnownSymbol$6 = wellKnownSymbol$e;
var TO_STRING_TAG = wellKnownSymbol$6("toStringTag");
var $Object = Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function() {
return arguments;
}()) == "Arguments";
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key) {
try {
return it[key];
} catch (error) {}
};
// getting tag from ES6+ `Object.prototype.toString`
var classof$4 = TO_STRING_TAG_SUPPORT ? classofRaw : function(it) {
var O, tag, result;
return it === undefined ? "Undefined" : it === null ? "Null" : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == "string" ? tag : CORRECT_ARGUMENTS ? classofRaw(O) : (result = classofRaw(O)) == "Object" && isCallable$6(O.callee) ? "Arguments" : result;
};
var classof$3 = classof$4;
var $String = String;
var toString$2 = function(argument) {
if (classof$3(argument) === "Symbol") throw TypeError("Cannot convert a Symbol value to a string");
return $String(argument);
};
var toPropertyKey = toPropertyKey$3;
var definePropertyModule$1 = objectDefineProperty;
var createPropertyDescriptor = createPropertyDescriptor$4;
var createProperty$1 = function(object, key, value) {
var propertyKey = toPropertyKey(key);
if (propertyKey in object) definePropertyModule$1.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var toAbsoluteIndex = toAbsoluteIndex$2;
var lengthOfArrayLike$3 = lengthOfArrayLike$5;
var createProperty = createProperty$1;
var $Array = Array;
var max = Math.max;
var arraySliceSimple = function(O, start, end) {
var length = lengthOfArrayLike$3(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
var result = $Array(max(fin - k, 0));
for(var n = 0; k < fin; k++, n++)createProperty(result, n, O[k]);
result.length = n;
return result;
};
var arraySlice$2 = arraySliceSimple;
var floor = Math.floor;
var mergeSort = function(array, comparefn) {
var length = array.length;
var middle = floor(length / 2);
return length < 8 ? insertionSort(array, comparefn) : merge(array, mergeSort(arraySlice$2(array, 0, middle), comparefn), mergeSort(arraySlice$2(array, middle), comparefn), comparefn);
};
var insertionSort = function(array, comparefn) {
var length = array.length;
var i = 1;
var element, j;
while(i < length){
j = i;
element = array[i];
while(j && comparefn(array[j - 1], element) > 0)array[j] = array[--j];
if (j !== i++) array[j] = element;
}
return array;
};
var merge = function(array, left, right, comparefn) {
var llength = left.length;
var rlength = right.length;
var lindex = 0;
var rindex = 0;
while(lindex < llength || rindex < rlength)array[lindex + rindex] = lindex < llength && rindex < rlength ? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++] : lindex < llength ? left[lindex++] : right[rindex++];
return array;
};
var arraySort = mergeSort;
var fails$3 = fails$f;
var arrayMethodIsStrict$2 = function(METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails$3(function() {
// eslint-disable-next-line no-useless-call -- required for testing
method.call(null, argument || function() {
return 1;
}, 1);
});
};
var userAgent$4 = engineUserAgent;
var firefox = userAgent$4.match(/firefox\/(\d+)/i);
var engineFfVersion = !!firefox && +firefox[1];
var UA = engineUserAgent;
var engineIsIeOrEdge = /MSIE|Trident/.test(UA);
var userAgent$3 = engineUserAgent;
var webkit = userAgent$3.match(/AppleWebKit\/(\d+)\./);
var engineWebkitVersion = !!webkit && +webkit[1];
var $$8 = _export;
var uncurryThis$4 = functionUncurryThis;
var aCallable$7 = aCallable$9;
var toObject$1 = toObject$5;
var lengthOfArrayLike$2 = lengthOfArrayLike$5;
var deletePropertyOrThrow = deletePropertyOrThrow$1;
var toString$1 = toString$2;
var fails$2 = fails$f;
var internalSort = arraySort;
var arrayMethodIsStrict$1 = arrayMethodIsStrict$2;
var FF = engineFfVersion;
var IE_OR_EDGE = engineIsIeOrEdge;
var V8 = engineV8Version;
var WEBKIT = engineWebkitVersion;
var test = [];
var un$Sort = uncurryThis$4(test.sort);
var push = uncurryThis$4(test.push);
// IE8-
var FAILS_ON_UNDEFINED = fails$2(function() {
test.sort(undefined);
});
// V8 bug
var FAILS_ON_NULL = fails$2(function() {
test.sort(null);
});
// Old WebKit
var STRICT_METHOD$1 = arrayMethodIsStrict$1("sort");
var STABLE_SORT = !fails$2(function() {
// feature detection can be too slow, so check engines versions
if (V8) return V8 < 70;
if (FF && FF > 3) return;
if (IE_OR_EDGE) return true;
if (WEBKIT) return WEBKIT < 603;
var result = "";
var code, chr, value, index;
// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for(code = 65; code < 76; code++){
chr = String.fromCharCode(code);
switch(code){
case 66:
case 69:
case 70:
case 72:
value = 3;
break;
case 68:
case 71:
value = 4;
break;
default:
value = 2;
}
for(index = 0; index < 47; index++)test.push({
k: chr + index,
v: value
});
}
test.sort(function(a, b) {
return b.v - a.v;
});
for(index = 0; index < test.length; index++){
chr = test[index].k.charAt(0);
if (result.charAt(result.length - 1) !== chr) result += chr;
}
return result !== "DGBEFHACIJK";
});
var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD$1 || !STABLE_SORT;
var getSortCompare = function(comparefn) {
return function(x, y) {
if (y === undefined) return -1;
if (x === undefined) return 1;
if (comparefn !== undefined) return +comparefn(x, y) || 0;
return toString$1(x) > toString$1(y) ? 1 : -1;
};
};
// `Array.prototype.sort` method
// https://tc39.es/ecma262/#sec-array.prototype.sort
$$8({
target: "Array",
proto: true,
forced: FORCED
}, {
sort: function sort(comparefn) {
if (comparefn !== undefined) aCallable$7(comparefn);
var array = toObject$1(this);
if (STABLE_SORT) return comparefn === undefined ? un$Sort(array) : un$Sort(array, comparefn);
var items = [];
var arrayLength = lengthOfArrayLike$2(array);
var itemsLength, index;
for(index = 0; index < arrayLength; index++)if (index in array) push(items, array[index]);
internalSort(items, getSortCompare(comparefn));
itemsLength = items.length;
index = 0;
while(index < itemsLength)array[index] = items[index++];
while(index < arrayLength)deletePropertyOrThrow(array, index++);
return array;
}
});
var aCallable$6 = aCallable$9;
var toObject = toObject$5;
var IndexedObject = indexedObject;
var lengthOfArrayLike$1 = lengthOfArrayLike$5;
var $TypeError$5 = TypeError;
// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod = function(IS_RIGHT) {
return function(that, callbackfn, argumentsLength, memo) {
aCallable$6(callbackfn);
var O = toObject(that);
var self1 = IndexedObject(O);
var length = lengthOfArrayLike$1(O);
var index = IS_RIGHT ? length - 1 : 0;
var i = IS_RIGHT ? -1 : 1;
if (argumentsLength < 2) while(true){
if (index in self1) {
memo = self1[index];
index += i;
break;
}
index += i;
if (IS_RIGHT ? index < 0 : length <= index) throw $TypeError$5("Reduce of empty array with no initial value");
}
for(; IS_RIGHT ? index >= 0 : length > index; index += i)if (index in self1) memo = callbackfn(memo, self1[index], index, O);
return memo;
};
};
var arrayReduce = {
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
left: createMethod(false),
// `Array.prototype.reduceRight` method
// https://tc39.es/ecma262/#sec-array.prototype.reduceright
right: createMethod(true)
};
var classof$2 = classofRaw$1;
var global$9 = global$k;
var engineIsNode = classof$2(global$9.process) == "process";
var $$7 = _export;
var $reduce = arrayReduce.left;
var arrayMethodIsStrict = arrayMethodIsStrict$2;
var CHROME_VERSION = engineV8Version;
var IS_NODE$3 = engineIsNode;
var STRICT_METHOD = arrayMethodIsStrict("reduce");
// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG = !IS_NODE$3 && CHROME_VERSION > 79 && CHROME_VERSION < 83;
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
$$7({
target: "Array",
proto: true,
forced: !STRICT_METHOD || CHROME_BUG
}, {
reduce: function reduce(callbackfn /* , initialValue */ ) {
var length = arguments.length;
return $reduce(this, callbackfn, length, length > 1 ? arguments[1] : undefined);
}
});
var $$6 = _export;
var DESCRIPTORS$1 = descriptors;
var global$8 = global$k;
var uncurryThis$3 = functionUncurryThis;
var hasOwn$1 = hasOwnProperty_1;
var isCallable$5 = isCallable$l;
var isPrototypeOf$2 = objectIsPrototypeOf;
var toString = toString$2;
var defineProperty = objectDefineProperty.f;
var copyConstructorProperties = copyConstructorProperties$2;
var NativeSymbol = global$8.Symbol;
var SymbolPrototype = NativeSymbol && NativeSymbol.prototype;
if (DESCRIPTORS$1 && isCallable$5(NativeSymbol) && (!("description" in SymbolPrototype) || // Safari 12 bug
NativeSymbol().description !== undefined)) {
var EmptyStringDescriptionStore = {};
// wrap Symbol constructor for correct work with undefined description
var SymbolWrapper = function Symbol1() {
var description = arguments.length < 1 || arguments[0] === undefined ? undefined : toString(arguments[0]);
var result = isPrototypeOf$2(SymbolPrototype, this) ? new NativeSymbol(description) : description === undefined ? NativeSymbol() : NativeSymbol(description);
if (description === "") EmptyStringDescriptionStore[result] = true;
return result;
};
copyConstructorProperties(SymbolWrapper, NativeSymbol);
SymbolWrapper.prototype = SymbolPrototype;
SymbolPrototype.constructor = SymbolWrapper;
var NATIVE_SYMBOL = String(NativeSymbol("test")) == "Symbol(test)";
var symbolToString = uncurryThis$3(SymbolPrototype.toString);
var symbolValueOf = uncurryThis$3(SymbolPrototype.valueOf);
var regexp = /^Symbol\((.*)\)[^)]+$/;
var replace = uncurryThis$3("".replace);
var stringSlice = uncurryThis$3("".slice);
defineProperty(SymbolPrototype, "description", {
configurable: true,
get: function description() {
var symbol = symbolValueOf(this);
var string = symbolToString(symbol);
if (hasOwn$1(EmptyStringDescriptionStore, symbol)) return "";
var desc = NATIVE_SYMBOL ? stringSlice(string, 7, -1) : replace(string, regexp, "$1");
return desc === "" ? undefined : desc;
}
});
$$6({
global: true,
constructor: true,
forced: true
}, {
Symbol: SymbolWrapper
});
}
const WalletOptions = ({ selector , handleWalletClick })=>{
const [modules, setModules] = (0, _react.useState)([]);
const [activeWalletId, setActiveWalletId] = (0, _react.useState)("");
(0, _react.useEffect)(()=>{
const subscription = selector.store.observable.subscribe((state)=>{
state.modules.sort((current, next)=>{
if (current.metadata.deprecated === next.metadata.deprecated) return 0;
return current.metadata.deprecated ? 1 : -1;
});
const { selectedWalletId } = selector.store.getState();
if (selectedWalletId) setActiveWalletId(selectedWalletId);
setModules(state.modules);
});
return ()=>subscription.unsubscribe(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (0, _jsxRuntime.jsx)("div", Object.assign({
className: "wallet-options-wrapper"
}, {
children: (0, _jsxRuntime.jsx)("ul", Object.assign({
className: "options-list"
}, {
children: modules.reduce((result, module, index)=>{
const { selectedWalletId } = selector.store.getState();
const { name , description , iconUrl , deprecated } = module.metadata;
const selected = module.id === selectedWalletId;
result.push((0, _jsxRuntime.jsxs)("li", Object.assign({
className: `single-wallet ${activeWalletId === module.id ? "selected-wallet" : ""} ${selected ? "connected-wallet" : ""} ${deprecated ? "deprecated-wallet" : ""} sidebar`,
onClick: ()=>{
if (module.id === modules[index].id) setActiveWalletId(module.id);
return handleWalletClick(module);
}
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "icon"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: iconUrl,
alt: name
})
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "title"
}, {
children: name
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "description"
}, {
children: description
}))
]
})),
deprecated && (0, _jsxRuntime.jsx)("div", Object.assign({
className: "warning-triangle"
}, {
children: (0, _jsxRuntime.jsxs)("svg", Object.assign({
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: [
(0, _jsxRuntime.jsx)("path", {
d: "M4.95215 16.3536L10.2152 5.85657C10.9531 4.38481 13.0538 4.38519 13.7912 5.85723L19.0494 16.3543C19.7156 17.6841 18.7486 19.25 17.2612 19.25H6.74001C5.25228 19.25 4.28535 17.6835 4.95215 16.3536Z",
stroke: "#E6B73E",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M12 10V12",
stroke: "#E6B73E",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M12.5 16C12.5 16.2761 12.2761 16.5 12 16.5C11.7239 16.5 11.5 16.2761 11.5 16C11.5 15.7239 11.7239 15.5 12 15.5C12.2761 15.5 12.5 15.7239 12.5 16Z",
stroke: "#E6B73E"
})
]
}))
}))
]
}), module.id));
return result;
}, [])
}))
}));
};
const ConnectionResult = ({ module , message , err , onRetry })=>{
return (0, _jsxRuntime.jsx)("div", Object.assign({
className: "connection connecting-details"
}, {
children: err ? (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "error-wrapper"
}, {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "error"
}, {
children: [
(0, _jsxRuntime.jsxs)("svg", Object.assign({
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http:/*www.w3.org/2000/svg"
}, {
children: [
"*/ ",
(0, _jsxRuntime.jsx)("rect", {
width: "24",
height: "24",
rx: "12",
fill: "#CE5A6F"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M17.25 6.75L6.75 17.25",
stroke: "currentColor",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M6.75 6.75L17.25 17.25",
stroke: "currentColor",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
]
})),
"Connection Failed"
]
})),
(0, _jsxRuntime.jsx)("p", {
children: message
}),
(module === null || module === void 0 ? void 0 : module.metadata.available) && (0, _jsxRuntime.jsx)("button", Object.assign({
onClick: onRetry
}, {
children: "Retry"
}))
]
})) : (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "success"
}, {
children: [
(0, _jsxRuntime.jsxs)("svg", Object.assign({
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: [
(0, _jsxRuntime.jsx)("rect", {
width: "24",
height: "24",
rx: "12",
fill: "#51BD7C"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M7.75 12.75L10 15.25L16.25 8.75",
stroke: "#232323",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
]
})),
"Connection Successful"
]
}))
}));
};
const AlertMessage = ({ message , module , onBack , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsx)(ModalHeader, {
title: "",
onCloseModal: onCloseModal
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "alert-message connecting-wrapper connecting-wrapper-err"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "icon"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: module === null || module === void 0 ? void 0 : module.metadata.iconUrl,
alt: module === null || module === void 0 ? void 0 : module.metadata.name
})
})),
(0, _jsxRuntime.jsx)("h3", Object.assign({
className: "connecting-name"
}, {
children: module === null || module === void 0 ? void 0 : module.metadata.name
})),
(0, _jsxRuntime.jsx)(ConnectionResult, {
module: module,
message: message,
err: message !== null,
onRetry: ()=>{
onBack(true);
}
})
]
}))
}))
]
});
};
var getBuiltIn$3 = getBuiltIn$8;
var definePropertyModule = objectDefineProperty;
var wellKnownSymbol$5 = wellKnownSymbol$e;
var DESCRIPTORS = descriptors;
var SPECIES$2 = wellKnownSymbol$5("species");
var setSpecies$1 = function(CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn$3(CONSTRUCTOR_NAME);
var defineProperty = definePropertyModule.f;
if (DESCRIPTORS && Constructor && !Constructor[SPECIES$2]) defineProperty(Constructor, SPECIES$2, {
configurable: true,
get: function() {
return this;
}
});
};
var isPrototypeOf$1 = objectIsPrototypeOf;
var $TypeError$4 = TypeError;
var anInstance$1 = function(it, Prototype) {
if (isPrototypeOf$1(Prototype, it)) return it;
throw $TypeError$4("Incorrect invocation");
};
var uncurryThis$2 = functionUncurryThis;
var fails$1 = fails$f;
var isCallable$4 = isCallable$l;
var classof$1 = classof$4;
var getBuiltIn$2 = getBuiltIn$8;
var inspectSource$1 = inspectSource$4;
var noop = function() {};
var empty = [];
var construct = getBuiltIn$2("Reflect", "construct");
var constructorRegExp = /^\s*(?:class|function)\b/;
var exec = uncurryThis$2(constructorRegExp.exec);
var INCORRECT_TO_STRING = !constructorRegExp.exec(noop);
var isConstructorModern = function isConstructor(argument) {
if (!isCallable$4(argument)) return false;
try {
construct(noop, empty, argument);
return true;
} catch (error) {
return false;
}
};
var isConstructorLegacy = function isConstructor(argument) {
if (!isCallable$4(argument)) return false;
switch(classof$1(argument)){
case "AsyncFunction":
case "GeneratorFunction":
case "AsyncGeneratorFunction":
return false;
}
try {
// we can't check .prototype since constructors produced by .bind haven't it
// `Function#toString` throws on some built-it function in some legacy engines
// (for example, `DOMQuad` and similar in FF41-)
return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource$1(argument));
} catch (error) {
return true;
}
};
isConstructorLegacy.sham = true;
// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
var isConstructor$1 = !construct || fails$1(function() {
var called;
return isConstructorModern(isConstructorModern.call) || !isConstructorModern(Object) || !isConstructorModern(function() {
called = true;
}) || called;
}) ? isConstructorLegacy : isConstructorModern;
var isConstructor = isConstructor$1;
var tryToString$2 = tryToString$5;
var $TypeError$3 = TypeError;
// `Assert: IsConstructor(argument) is true`
var aConstructor$1 = function(argument) {
if (isConstructor(argument)) return argument;
throw $TypeError$3(tryToString$2(argument) + " is not a constructor");
};
var anObject$4 = anObject$a;
var aConstructor = aConstructor$1;
var wellKnownSymbol$4 = wellKnownSymbol$e;
var SPECIES$1 = wellKnownSymbol$4("species");
// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
var speciesConstructor$1 = function(O, defaultConstructor) {
var C = anObject$4(O).constructor;
var S;
return C === undefined || (S = anObject$4(C)[SPECIES$1]) == undefined ? defaultConstructor : aConstructor(S);
};
var NATIVE_BIND$1 = functionBindNative;
var FunctionPrototype = Function.prototype;
var apply$1 = FunctionPrototype.apply;
var call$7 = FunctionPrototype.call;
// eslint-disable-next-line es-x/no-reflect -- safe
var functionApply = typeof Reflect == "object" && Reflect.apply || (NATIVE_BIND$1 ? call$7.bind(apply$1) : function() {
return call$7.apply(apply$1, arguments);
});
var uncurryThis$1 = functionUncurryThis;
var aCallable$5 = aCallable$9;
var NATIVE_BIND = functionBindNative;
var bind$4 = uncurryThis$1(uncurryThis$1.bind);
// optional / simple context binding
var functionBindContext = function(fn, that) {
aCallable$5(fn);
return that === undefined ? fn : NATIVE_BIND ? bind$4(fn, that) : function() {
return fn.apply(that, arguments);
};
};
var uncurryThis = functionUncurryThis;
var arraySlice$1 = uncurryThis([].slice);
var $TypeError$2 = TypeError;
var validateArgumentsLength$1 = function(passed, required) {
if (passed < required) throw $TypeError$2("Not enough arguments");
return passed;
};
var userAgent$2 = engineUserAgent;
var engineIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent$2);
var global$7 = global$k;
var apply = functionApply;
var bind$3 = functionBindContext;
var isCallable$3 = isCallable$l;
var hasOwn = hasOwnProperty_1;
var fails = fails$f;
var html = html$2;
var arraySlice = arraySlice$1;
var createElement = documentCreateElement$2;
var validateArgumentsLength = validateArgumentsLength$1;
var IS_IOS$1 = engineIsIos;
var IS_NODE$2 = engineIsNode;
var set = global$7.setImmediate;
var clear = global$7.clearImmediate;
var process$2 = global$7.process;
var Dispatch = global$7.Dispatch;
var Function$1 = global$7.Function;
var MessageChannel = global$7.MessageChannel;
var String$1 = global$7.String;
var counter = 0;
var queue$1 = {};
var ONREADYSTATECHANGE = "onreadystatechange";
var location, defer, channel, port;
try {
// Deno throws a ReferenceError on `location` access without `--location` flag
location = global$7.location;
} catch (error1) {}
var run = function(id) {
if (hasOwn(queue$1, id)) {
var fn = queue$1[id];
delete queue$1[id];
fn();
}
};
var runner = function(id) {
return function() {
run(id);
};
};
var listener = function(event) {
run(event.data);
};
var post = function(id) {
// old engines have not location.origin
global$7.postMessage(String$1(id), location.protocol + "//" + location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set || !clear) {
set = function setImmediate(handler) {
validateArgumentsLength(arguments.length, 1);
var fn = isCallable$3(handler) ? handler : Function$1(handler);
var args = arraySlice(arguments, 1);
queue$1[++counter] = function() {
apply(fn, undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue$1[id];
};
// Node.js 0.8-
if (IS_NODE$2) defer = function(id) {
process$2.nextTick(runner(id));
};
else if (Dispatch && Dispatch.now) defer = function(id) {
Dispatch.now(runner(id));
};
else if (MessageChannel && !IS_IOS$1) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = bind$3(port.postMessage, port);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global$7.addEventListener && isCallable$3(global$7.postMessage) && !global$7.importScripts && location && location.protocol !== "file:" && !fails(post)) {
defer = post;
global$7.addEventListener("message", listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in createElement("script")) defer = function(id) {
html.appendChild(createElement("script"))[ONREADYSTATECHANGE] = function() {
html.removeChild(this);
run(id);
};
};
else defer = function(id) {
setTimeout(runner(id), 0);
};
}
var task$1 = {
set: set,
clear: clear
};
var userAgent$1 = engineUserAgent;
var global$6 = global$k;
var engineIsIosPebble = /ipad|iphone|ipod/i.test(userAgent$1) && global$6.Pebble !== undefined;
var userAgent = engineUserAgent;
var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(userAgent);
var global$5 = global$k;
var bind$2 = functionBindContext;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var macrotask = task$1.set;
var IS_IOS = engineIsIos;
var IS_IOS_PEBBLE = engineIsIosPebble;
var IS_WEBOS_WEBKIT = engineIsWebosWebkit;
var IS_NODE$1 = engineIsNode;
var MutationObserver = global$5.MutationObserver || global$5.WebKitMutationObserver;
var document$2 = global$5.document;
var process$1 = global$5.process;
var Promise$1 = global$5.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global$5, "queueMicrotask");
var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
var flush, head, last, notify$1, toggle, node, promise, then;
// modern engines have queueMicrotask method
if (!queueMicrotask) {
flush = function() {
var parent, fn;
if (IS_NODE$1 && (parent = process$1.domain)) parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch (error) {
if (head) notify$1();
else last = undefined;
throw error;
}
}
last = undefined;
if (parent) parent.enter();
};
// browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
// also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
if (!IS_IOS && !IS_NODE$1 && !IS_WEBOS_WEBKIT && MutationObserver && document$2) {
toggle = true;
node = document$2.createTextNode("");
new MutationObserver(flush).observe(node, {
characterData: true
});
notify$1 = function() {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (!IS_IOS_PEBBLE && Promise$1 && Promise$1.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
promise = Promise$1.resolve(undefined);
// workaround of WebKit ~ iOS Safari 10.1 bug
promise.constructor = Promise$1;
then = bind$2(promise.then, promise);
notify$1 = function() {
then(flush);
};
// Node.js without promises
} else if (IS_NODE$1) notify$1 = function() {
process$1.nextTick(flush);
};
else {
// strange IE + webpack dev server bug - use .bind(global)
macrotask = bind$2(macrotask, global$5);
notify$1 = function() {
macrotask(flush);
};
}
}
var microtask$1 = queueMicrotask || function(fn) {
var task = {
fn: fn,
next: undefined
};
if (last) last.next = task;
if (!head) {
head = task;
notify$1();
}
last = task;
};
var global$4 = global$k;
var hostReportErrors$1 = function(a, b) {
var console = global$4.console;
if (console && console.error) arguments.length == 1 ? console.error(a) : console.error(a, b);
};
var perform$3 = function(exec) {
try {
return {
error: false,
value: exec()
};
} catch (error) {
return {
error: true,
value: error
};
}
};
var Queue$1 = function() {
this.head = null;
this.tail = null;
};
Queue$1.prototype = {
add: function(item) {
var entry = {
item: item,
next: null
};
if (this.head) this.tail.next = entry;
else this.head = entry;
this.tail = entry;
},
get: function() {
var entry = this.head;
if (entry) {
this.head = entry.next;
if (this.tail === entry) this.tail = null;
return entry.item;
}
}
};
var queue = Queue$1;
var global$3 = global$k;
var promiseNativeConstructor = global$3.Promise;
var engineIsBrowser = typeof window == "object" && typeof Deno != "object";
var global$2 = global$k;
var NativePromiseConstructor$3 = promiseNativeConstructor;
var isCallable$2 = isCallable$l;
var isForced = isForced_1;
var inspectSource = inspectSource$4;
var wellKnownSymbol$3 = wellKnownSymbol$e;
var IS_BROWSER = engineIsBrowser;
var V8_VERSION = engineV8Version;
NativePromiseConstructor$3 && NativePromiseConstructor$3.prototype;
var SPECIES = wellKnownSymbol$3("species");
var SUBCLASSING = false;
var NATIVE_PROMISE_REJECTION_EVENT$1 = isCallable$2(global$2.PromiseRejectionEvent);
var FORCED_PROMISE_CONSTRUCTOR$5 = isForced("Promise", function() {
var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor$3);
var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor$3);
// V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// We can't detect it synchronously, so just check versions
if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
// We can't use @@species feature detection in V8 since it causes
// deoptimization and performance degradation
// https://github.com/zloirock/core-js/issues/679
if (V8_VERSION >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false;
// Detect correctness of subclassing with @@species support
var promise = new NativePromiseConstructor$3(function(resolve) {
resolve(1);
});
var FakePromise = function(exec) {
exec(function() {}, function() {});
};
var constructor = promise.constructor = {};
constructor[SPECIES] = FakePromise;
SUBCLASSING = promise.then(function() {}) instanceof FakePromise;
if (!SUBCLASSING) return true;
// Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return !GLOBAL_CORE_JS_PROMISE && IS_BROWSER && !NATIVE_PROMISE_REJECTION_EVENT$1;
});
var promiseConstructorDetection = {
CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR$5,
REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT$1,
SUBCLASSING: SUBCLASSING
};
var newPromiseCapability$2 = {};
var aCallable$4 = aCallable$9;
var PromiseCapability = function(C) {
var resolve, reject;
this.promise = new C(function($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError("Bad Promise constructor");
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aCallable$4(resolve);
this.reject = aCallable$4(reject);
};
// `NewPromiseCapability` abstract operation
// https://tc39.es/ecma262/#sec-newpromisecapability
newPromiseCapability$2.f = function(C) {
return new PromiseCapability(C);
};
var $$5 = _export;
var IS_NODE = engineIsNode;
var global$1 = global$k;
var call$6 = functionCall;
var defineBuiltIn$1 = defineBuiltIn$5;
var setPrototypeOf = objectSetPrototypeOf;
var setToStringTag = setToStringTag$3;
var setSpecies = setSpecies$1;
var aCallable$3 = aCallable$9;
var isCallable$1 = isCallable$l;
var isObject$1 = isObject$7;
var anInstance = anInstance$1;
var speciesConstructor = speciesConstructor$1;
var task = task$1.set;
var microtask = microtask$1;
var hostReportErrors = hostReportErrors$1;
var perform$2 = perform$3;
var Queue = queue;
var InternalStateModule = internalState;
var NativePromiseConstructor$2 = promiseNativeConstructor;
var PromiseConstructorDetection = promiseConstructorDetection;
var newPromiseCapabilityModule$3 = newPromiseCapability$2;
var PROMISE = "Promise";
var FORCED_PROMISE_CONSTRUCTOR$4 = PromiseConstructorDetection.CONSTRUCTOR;
var NATIVE_PROMISE_REJECTION_EVENT = PromiseConstructorDetection.REJECTION_EVENT;
var NATIVE_PROMISE_SUBCLASSING = PromiseConstructorDetection.SUBCLASSING;
var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
var setInternalState = InternalStateModule.set;
var NativePromisePrototype$1 = NativePromiseConstructor$2 && NativePromiseConstructor$2.prototype;
var PromiseConstructor = NativePromiseConstructor$2;
var PromisePrototype = NativePromisePrototype$1;
var TypeError$1 = global$1.TypeError;
var document$1 = global$1.document;
var process = global$1.process;
var newPromiseCapability$1 = newPromiseCapabilityModule$3.f;
var newGenericPromiseCapability = newPromiseCapability$1;
var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && global$1.dispatchEvent);
var UNHANDLED_REJECTION = "unhandledrejection";
var REJECTION_HANDLED = "rejectionhandled";
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
// helpers
var isThenable = function(it) {
var then;
return isObject$1(it) && isCallable$1(then = it.then) ? then : false;
};
var callReaction = function(reaction, state) {
var value = state.value;
var ok = state.state == FULFILLED;
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (state.rejection === UNHANDLED) onHandleUnhandled(state);
state.rejection = HANDLED;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // can throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) reject(TypeError$1("Promise-chain cycle"));
else if (then = isThenable(result)) call$6(then, result, resolve, reject);
else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
};
var notify = function(state, isReject) {
if (state.notified) return;
state.notified = true;
microtask(function() {
var reactions = state.reactions;
var reaction;
while(reaction = reactions.get())callReaction(reaction, state);
state.notified = false;
if (isReject && !state.rejection) onUnhandled(state);
});
};
var dispatchEvent = function(name, promise, reason) {
var event, handler;
if (DISPATCH_EVENT) {
event = document$1.createEvent("Event");
event.promise = promise;
event.reason = reason;
event.initEvent(name, false, true);
global$1.dispatchEvent(event);
} else event = {
promise: promise,
reason: reason
};
if (!NATIVE_PROMISE_REJECTION_EVENT && (handler = global$1["on" + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors("Unhandled promise rejection", reason);
};
var onUnhandled = function(state) {
call$6(task, global$1, function() {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform$2(function() {
if (IS_NODE) process.emit("unhandledRejection", value, promise);
else dispatchEvent(UNHANDLED_REJECTION, promise, value);
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function(state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function(state) {
call$6(task, global$1, function() {
var promise = state.facade;
if (IS_NODE) process.emit("rejectionHandled", promise);
else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind$1 = function(fn, state, unwrap) {
return function(value) {
fn(state, value, unwrap);
};
};
var internalReject = function(state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
state.value = value;
state.state = REJECTED;
notify(state, true);
};
var internalResolve = function(state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
try {
if (state.facade === value) throw TypeError$1("Promise can't be resolved itself");
var then = isThenable(value);
if (then) microtask(function() {
var wrapper = {
done: false
};
try {
call$6(then, value, bind$1(internalResolve, wrapper, state), bind$1(internalReject, wrapper, state));
} catch (error) {
internalReject(wrapper, error, state);
}
});
else {
state.value = value;
state.state = FULFILLED;
notify(state, false);
}
} catch (error) {
internalReject({
done: false
}, error, state);
}
};
// constructor polyfill
if (FORCED_PROMISE_CONSTRUCTOR$4) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise1(executor) {
anInstance(this, PromisePrototype);
aCallable$3(executor);
call$6(Internal, this);
var state = getInternalPromiseState(this);
try {
executor(bind$1(internalResolve, state), bind$1(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
PromisePrototype = PromiseConstructor.prototype;
// eslint-disable-next-line no-unused-vars -- required for `.length`
Internal = function Promise1(executor) {
setInternalState(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: new Queue(),
rejection: false,
state: PENDING,
value: undefined
});
};
// `Promise.prototype.then` method
// https://tc39.es/ecma262/#sec-promise.prototype.then
Internal.prototype = defineBuiltIn$1(PromisePrototype, "then", function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor));
state.parent = true;
reaction.ok = isCallable$1(onFulfilled) ? onFulfilled : true;
reaction.fail = isCallable$1(onRejected) && onRejected;
reaction.domain = IS_NODE ? process.domain : undefined;
if (state.state == PENDING) state.reactions.add(reaction);
else microtask(function() {
callReaction(reaction, state);
});
return reaction.promise;
});
OwnPromiseCapability = function() {
var promise = new Internal();
var state = getInternalPromiseState(promise);
this.promise = promise;
this.resolve = bind$1(internalResolve, state);
this.reject = bind$1(internalReject, state);
};
newPromiseCapabilityModule$3.f = newPromiseCapability$1 = function(C) {
return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C);
};
if (isCallable$1(NativePromiseConstructor$2) && NativePromisePrototype$1 !== Object.prototype) {
nativeThen = NativePromisePrototype$1.then;
if (!NATIVE_PROMISE_SUBCLASSING) // make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
defineBuiltIn$1(NativePromisePrototype$1, "then", function then(onFulfilled, onRejected) {
var that = this;
return new PromiseConstructor(function(resolve, reject) {
call$6(nativeThen, that, resolve, reject);
}).then(onFulfilled, onRejected);
// https://github.com/zloirock/core-js/issues/640
}, {
unsafe: true
});
// make `.constructor === Promise` work for native promise-based APIs
try {
delete NativePromisePrototype$1.constructor;
} catch (error2) {}
// make `instanceof Promise` work for native promise-based APIs
if (setPrototypeOf) setPrototypeOf(NativePromisePrototype$1, PromisePrototype);
}
}
$$5({
global: true,
constructor: true,
wrap: true,
forced: FORCED_PROMISE_CONSTRUCTOR$4
}, {
Promise: PromiseConstructor
});
setToStringTag(PromiseConstructor, PROMISE, false);
setSpecies(PROMISE);
var wellKnownSymbol$2 = wellKnownSymbol$e;
var Iterators$1 = iterators;
var ITERATOR$2 = wellKnownSymbol$2("iterator");
var ArrayPrototype = Array.prototype;
// check on default Array iterator
var isArrayIteratorMethod$1 = function(it) {
return it !== undefined && (Iterators$1.Array === it || ArrayPrototype[ITERATOR$2] === it);
};
var classof = classof$4;
var getMethod$1 = getMethod$3;
var Iterators = iterators;
var wellKnownSymbol$1 = wellKnownSymbol$e;
var ITERATOR$1 = wellKnownSymbol$1("iterator");
var getIteratorMethod$2 = function(it) {
if (it != undefined) return getMethod$1(it, ITERATOR$1) || getMethod$1(it, "@@iterator") || Iterators[classof(it)];
};
var call$5 = functionCall;
var aCallable$2 = aCallable$9;
var anObject$3 = anObject$a;
var tryToString$1 = tryToString$5;
var getIteratorMethod$1 = getIteratorMethod$2;
var $TypeError$1 = TypeError;
var getIterator$1 = function(argument, usingIterator) {
var iteratorMethod = arguments.length < 2 ? getIteratorMethod$1(argument) : usingIterator;
if (aCallable$2(iteratorMethod)) return anObject$3(call$5(iteratorMethod, argument));
throw $TypeError$1(tryToString$1(argument) + " is not iterable");
};
var call$4 = functionCall;
var anObject$2 = anObject$a;
var getMethod = getMethod$3;
var iteratorClose$1 = function(iterator, kind, value) {
var innerResult, innerError;
anObject$2(iterator);
try {
innerResult = getMethod(iterator, "return");
if (!innerResult) {
if (kind === "throw") throw value;
return value;
}
innerResult = call$4(innerResult, iterator);
} catch (error) {
innerError = true;
innerResult = error;
}
if (kind === "throw") throw value;
if (innerError) throw innerResult;
anObject$2(innerResult);
return value;
};
var bind = functionBindContext;
var call$3 = functionCall;
var anObject$1 = anObject$a;
var tryToString = tryToString$5;
var isArrayIteratorMethod = isArrayIteratorMethod$1;
var lengthOfArrayLike = lengthOfArrayLike$5;
var isPrototypeOf = objectIsPrototypeOf;
var getIterator = getIterator$1;
var getIteratorMethod = getIteratorMethod$2;
var iteratorClose = iteratorClose$1;
var $TypeError = TypeError;
var Result = function(stopped, result) {
this.stopped = stopped;
this.result = result;
};
var ResultPrototype = Result.prototype;
var iterate$2 = function(iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = bind(unboundFunction, that);
var iterator, iterFn, index, length, result, next, step;
var stop = function(condition) {
if (iterator) iteratorClose(iterator, "normal", condition);
return new Result(true, condition);
};
var callFn = function(value) {
if (AS_ENTRIES) {
anObject$1(value);
return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
}
return INTERRUPTED ? fn(value, stop) : fn(value);
};
if (IS_ITERATOR) iterator = iterable;
else {
iterFn = getIteratorMethod(iterable);
if (!iterFn) throw $TypeError(tryToString(iterable) + " is not iterable");
// optimisation for array iterators
if (isArrayIteratorMethod(iterFn)) {
for(index = 0, length = lengthOfArrayLike(iterable); length > index; index++){
result = callFn(iterable[index]);
if (result && isPrototypeOf(ResultPrototype, result)) return result;
}
return new Result(false);
}
iterator = getIterator(iterable, iterFn);
}
next = iterator.next;
while(!(step = call$3(next, iterator)).done){
try {
result = callFn(step.value);
} catch (error) {
iteratorClose(iterator, "throw", error);
}
if (typeof result == "object" && result && isPrototypeOf(ResultPrototype, result)) return result;
}
return new Result(false);
};
var wellKnownSymbol = wellKnownSymbol$e;
var ITERATOR = wellKnownSymbol("iterator");
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function() {
return {
done: !!called++
};
},
"return": function() {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR] = function() {
return this;
};
// eslint-disable-next-line es-x/no-array-from, no-throw-literal -- required for testing
Array.from(iteratorWithReturn, function() {
throw 2;
});
} catch (error3) {}
var checkCorrectnessOfIteration$1 = function(exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR] = function() {
return {
next: function() {
return {
done: ITERATION_SUPPORT = true
};
}
};
};
exec(object);
} catch (error) {}
return ITERATION_SUPPORT;
};
var NativePromiseConstructor$1 = promiseNativeConstructor;
var checkCorrectnessOfIteration = checkCorrectnessOfIteration$1;
var FORCED_PROMISE_CONSTRUCTOR$3 = promiseConstructorDetection.CONSTRUCTOR;
var promiseStaticsIncorrectIteration = FORCED_PROMISE_CONSTRUCTOR$3 || !checkCorrectnessOfIteration(function(iterable) {
NativePromiseConstructor$1.all(iterable).then(undefined, function() {});
});
var $$4 = _export;
var call$2 = functionCall;
var aCallable$1 = aCallable$9;
var newPromiseCapabilityModule$2 = newPromiseCapability$2;
var perform$1 = perform$3;
var iterate$1 = iterate$2;
var PROMISE_STATICS_INCORRECT_ITERATION$1 = promiseStaticsIncorrectIteration;
// `Promise.all` method
// https://tc39.es/ecma262/#sec-promise.all
$$4({
target: "Promise",
stat: true,
forced: PROMISE_STATICS_INCORRECT_ITERATION$1
}, {
all: function all(iterable) {
var C = this;
var capability = newPromiseCapabilityModule$2.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform$1(function() {
var $promiseResolve = aCallable$1(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate$1(iterable, function(promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
call$2($promiseResolve, C, promise).then(function(value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var $$3 = _export;
var FORCED_PROMISE_CONSTRUCTOR$2 = promiseConstructorDetection.CONSTRUCTOR;
var NativePromiseConstructor = promiseNativeConstructor;
var getBuiltIn$1 = getBuiltIn$8;
var isCallable = isCallable$l;
var defineBuiltIn = defineBuiltIn$5;
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
// `Promise.prototype.catch` method
// https://tc39.es/ecma262/#sec-promise.prototype.catch
$$3({
target: "Promise",
proto: true,
forced: FORCED_PROMISE_CONSTRUCTOR$2,
real: true
}, {
"catch": function(onRejected) {
return this.then(undefined, onRejected);
}
});
// makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
if (isCallable(NativePromiseConstructor)) {
var method = getBuiltIn$1("Promise").prototype["catch"];
if (NativePromisePrototype["catch"] !== method) defineBuiltIn(NativePromisePrototype, "catch", method, {
unsafe: true
});
}
var $$2 = _export;
var call$1 = functionCall;
var aCallable = aCallable$9;
var newPromiseCapabilityModule$1 = newPromiseCapability$2;
var perform = perform$3;
var iterate = iterate$2;
var PROMISE_STATICS_INCORRECT_ITERATION = promiseStaticsIncorrectIteration;
// `Promise.race` method
// https://tc39.es/ecma262/#sec-promise.race
$$2({
target: "Promise",
stat: true,
forced: PROMISE_STATICS_INCORRECT_ITERATION
}, {
race: function race(iterable) {
var C = this;
var capability = newPromiseCapabilityModule$1.f(C);
var reject = capability.reject;
var result = perform(function() {
var $promiseResolve = aCallable(C.resolve);
iterate(iterable, function(promise) {
call$1($promiseResolve, C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var $$1 = _export;
var call = functionCall;
var newPromiseCapabilityModule = newPromiseCapability$2;
var FORCED_PROMISE_CONSTRUCTOR$1 = promiseConstructorDetection.CONSTRUCTOR;
// `Promise.reject` method
// https://tc39.es/ecma262/#sec-promise.reject
$$1({
target: "Promise",
stat: true,
forced: FORCED_PROMISE_CONSTRUCTOR$1
}, {
reject: function reject(r) {
var capability = newPromiseCapabilityModule.f(this);
call(capability.reject, undefined, r);
return capability.promise;
}
});
var anObject = anObject$a;
var isObject = isObject$7;
var newPromiseCapability = newPromiseCapability$2;
var promiseResolve$1 = function(C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
var $ = _export;
var getBuiltIn = getBuiltIn$8;
var FORCED_PROMISE_CONSTRUCTOR = promiseConstructorDetection.CONSTRUCTOR;
var promiseResolve = promiseResolve$1;
getBuiltIn("Promise");
// `Promise.resolve` method
// https://tc39.es/ecma262/#sec-promise.resolve
$({
target: "Promise",
stat: true,
forced: FORCED_PROMISE_CONSTRUCTOR
}, {
resolve: function resolve(x) {
return promiseResolve(this, x);
}
});
const HardwareWalletAccountsForm = ({ accounts , onSelectedChanged , onSubmit , onChangeRoute })=>{
return (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "choose-ledger-account-form-wrapper"
}, {
children: [
(0, _jsxRuntime.jsxs)("p", {
children: [
"We found ",
accounts.length,
" accounts on your device. Select the account(s) you wish to connect."
]
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "button-wrapper"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
onClick: ()=>{
onChangeRoute("SpecifyHDPath");
}
}, {
children: "HD.../0"
}))
})),
(0, _jsxRuntime.jsx)("form", Object.assign({
className: "form",
onSubmit: (e)=>{
onSubmit(accounts, e);
}
}, {
children: (0, _jsxRuntime.jsxs)("div", {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "nws-form-control"
}, {
children: accounts.map((account, index)=>(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "account"
}, {
children: [
(0, _jsxRuntime.jsx)("input", {
onChange: (e)=>{
onSelectedChanged(index, e.target.checked);
},
checked: account.selected,
type: "checkbox",
id: account.accountId,
name: account.accountId,
value: account.accountId
}),
(0, _jsxRuntime.jsxs)("label", Object.assign({
htmlFor: account.accountId
}, {
children: [
" ",
account.accountId
]
})),
(0, _jsxRuntime.jsx)("br", {})
]
}), index))
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
type: "submit",
disabled: !accounts.some((x)=>x.selected)
}, {
children: "Connect"
}))
}))
]
})
}))
]
}));
};
var img$1 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAR3SURBVHgBpVZ9aJVVGH+e55z33bi7zY9hMz+yMAeNoEIq6A9ZRKQWEsQNFIIpsf5Y9E+GsD9iBEEDMUkDa6ShRKKZYIWiRkaKaUGUGCKOTGMF84PNO99773vOefq9720yK5ZzD/dwPt/nd37P17lEk5Qnuz9roUkKT7T5bNe+QjTNLCHv24h1Xgh+OmtwQYPH2jUXwlnW9NRooqePfLS6MmmQ59cdeEGJlkJZA5MGVecoAwghBYZTVY9ftuaDSy8x8w9fbFl95JZAXuw9dmelkvRAyXxS7wMFryG4bIyWZiqzPgMhaFfGfn3NY3AZG9sPf/Dy8HidZvxkZc/h1pqnPlKey6yspMqUd9jVAEYY6RCGDQTwjGDwGTgAlbwRijV1C9vanz577tT+6r+YrOz5rlXFrQ/qZ+FbDxCfXS5oOgxln4v473f3rbgwdn7FK5/MCaH2eAg6X8g3K2iBMTiBkNJVKbod+ze9mgPZsY/UaicYzCE1HgpZc558olCTjTvWLxv9p1n3bV45iO7T5zq3TU9j9xTOLwQ5D9t48aEYrtGj2P/2BpNS78nZJoRdlDsYd8vphz273lqyhW5Rnlnz3hOe6SEwghvxPUMTVfYe2rpuUOqOkZeIxdSbsSJ8eTIAmXy5tftrMPkzi0C4B2ZDNHp+INvLQURkhYiJ6gDGko376DbEJ8k3mcnYBSeSM2ptL/XGsurNnxfnDIQNwCKADO1845Ef6Tbk0M51g4joMgncDyBmkrtsNEMQovcDxGYsGL2yDNAUxPv0VySs4yxhfeYbabJg0Awg+ILylEB6nKMpSOp0WCR1+QSuD4ELljNDEfyRrdXPCU1BTEgD7pyOzVmC2iBm0KgYAMCEeXovoClIjdKiVdQ3FYbzmatxWRqMPcNsDHyfNWskWk5TkJhNEwVyxA6hLL5clLJsW7voFxa6LiR5CCOeWzo3XFxKtyEdy3tnp7VahAoDp6PEVGvJye09l3P7K9k9WQijXBv4B6WG+0pvD0ybFEBHZ6OPh+/OGaBsIvNRAGp/ZHv1jJeon+omszBkFsr3FhsLB7rev3JLQKVSyfjmaW2BJSavDlqR7c5VrR+4AbLttbkXMehH7gjA8gZiD/tq+Or/ABZ3dUW/J62LcPUGcrW8pKSVFAg6cHz3O0l25qZHa/XGwWPg9aAwwzdZAaDX+7tbNsMYf5+bpaUS0dDQEF8rtsUxCbI5e5KRzGhBMiqNxllKju7d8NOYXjseRBytQngcVDL3wD9H+7vf3YS7mnnzqrZpwSxrwkh04cpM5NTMyJdHbIgaESyxJ6tZ5cDbw3qd0tqVCp25Se/4yYdr5/zm/ehjwvpxZHgN0Wlub0/Yt7awdykqRYFHy6NUQVrBd4o6p6ngrVL2Bo8ksuJqoXzq9Ln9m6rj9U74b6Wjo8OeP082aY5NUxRsYzwDkeFsU+MdUU3U4PG0QtbahqhadDMuHTy4fvS/9EwIUpdeuW/ZiShOipFxURRbNdWETFMRZrCFlEZGkuPHdycTafgLExNiI6YfUpcAAAAASUVORK5CYII=";
const WalletConnecting = ({ wallet , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsx)(ModalHeader, {
title: "",
onCloseModal: onCloseModal
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "connecting-wrapper"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "icon"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: wallet === null || wallet === void 0 ? void 0 : wallet.metadata.iconUrl,
alt: wallet === null || wallet === void 0 ? void 0 : wallet.metadata.name
})
})),
(0, _jsxRuntime.jsx)("h3", Object.assign({
className: "connecting-name"
}, {
children: wallet === null || wallet === void 0 ? void 0 : wallet.metadata.name
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "connecting-details"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "spinner"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: img$1,
alt: "loading-icon"
})
})),
(0, _jsxRuntime.jsxs)("span", {
children: [
"Connecting to ",
wallet === null || wallet === void 0 ? void 0 : wallet.metadata.name,
"..."
]
})
]
}))
]
}))
}))
]
});
};
const LedgerDeviceIcon = ()=>{
return (0, _jsxRuntime.jsxs)("svg", Object.assign({
width: "317",
height: "157",
viewBox: "0 0 317 157",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: [
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M249.99 16.0994C270.063 -0.864155 289.788 1.58873 301.497 10.7365C307.402 15.3499 311.278 21.6575 312.267 28.1258C313.247 34.5412 311.413 41.2233 305.692 46.8044C297.366 54.9273 286.343 55.3362 273.015 51.5109C261.654 48.25 249.058 42.0377 235.726 35.4627L235.726 35.4626L235.717 35.458C233.367 34.2992 230.995 33.129 228.602 31.9618C212.742 24.2253 196.067 16.6575 179.842 13.8595C163.538 11.0479 147.552 13.0313 133.266 24.522C128.032 28.732 123.478 35.2086 121.716 44.8205C119.961 54.3947 120.992 66.9771 126.703 83.4311C135.432 108.583 132.899 126.677 123.575 138.063C114.217 149.491 97.5614 154.733 76.7887 153.121C55.0043 151.43 29.0621 142.206 3.29867 125.227L0.887817 127.942C27.2472 145.405 53.9251 154.952 76.5105 156.705C97.9028 158.365 115.96 153.035 126.356 140.341C136.785 127.606 139.045 108.029 130.099 82.2524C124.521 66.1801 123.642 54.2493 125.252 45.4687C126.854 36.7258 130.94 31.006 135.519 27.3232C148.794 16.6458 163.649 14.715 179.231 17.4021C194.891 20.1027 211.146 27.4463 227.026 35.1928C229.381 36.3415 231.729 37.5001 234.066 38.6531L234.073 38.6568C247.382 45.223 260.324 51.608 272.024 54.9662C285.819 58.9258 298.493 58.8501 308.202 49.3776C314.764 42.9759 316.974 35.1288 315.82 27.5826C314.675 20.0893 310.237 13.0029 303.71 7.90363C290.555 -2.37382 268.938 -4.62038 247.67 13.3537L249.99 16.0994Z",
fill: "url(#paint0_linear_3_672)"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M260.264 17.8767L177.605 89.4649L157.679 73.9664L239.23 3.85423L260.264 17.8767Z",
fill: "#6A7075"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M205.939 54.4577L199.764 50.2636L233.316 20.9053L239.907 25.8395L205.939 54.4577Z",
fill: "#494E52"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M260.264 17.8757L177.605 89.4639L182.033 98.3202L264.323 26.363L260.264 17.8757Z",
fill: "#494E52"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M177.236 89.4646L181.295 98.3209L165.059 85.7745L170.963 85.0365L177.236 89.4646Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M93.4708 99.6384L91.9948 110.13L174.653 92.894L164.69 85.7749L93.4708 99.6384Z",
fill: "#DCDADA"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M93.1157 104.323L94.314 100.129L165.613 86.3483L169.208 89.344L93.1157 104.323Z",
fill: "#C1C1C1"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M94.2086 99.7963L86.0903 101.272L92.3635 110.129L94.2086 99.7963Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M86.0903 100.907L89.0027 74.1304L178.455 55.2416C184.695 53.9962 195.766 54.7675 197.177 63.7058C198.284 70.717 195.506 73.9943 191.628 77.3592C188.495 80.0671 180.152 82.4646 178.343 82.8944C178.293 82.9064 178.241 82.9188 178.186 82.9319C177.38 83.1245 176.007 83.4525 170.644 84.5088C169.085 84.8158 167.382 85.1501 165.557 85.5078L164.933 85.63C146.312 89.2764 115.528 95.2297 93.9844 99.3849C91.1808 99.9257 88.5337 100.436 86.0903 100.907ZM185.076 75.554C190.748 73.3535 193.99 68.0745 192.318 63.7631C190.645 59.4517 184.691 57.7405 179.019 59.941C173.347 62.1416 170.105 67.4206 171.778 71.732C173.45 76.0434 179.404 77.7546 185.076 75.554Z",
fill: "#F4F1E8"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M199.764 50.3994L196.768 48.3043L232.194 18.0454L233.316 21.6403L199.764 50.3994Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M239.968 25.9943L232.588 20.4592V17.5071L241.813 24.5183L239.968 25.9943Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("ellipse", {
cx: "182.084",
cy: "68.0811",
rx: "10.242",
ry: "7.46772",
transform: "rotate(-23.7949 182.084 68.0811)",
fill: "#494E52"
}),
(0, _jsxRuntime.jsx)("ellipse", {
cx: "182.084",
cy: "68.0816",
rx: "6.68462",
ry: "4.87394",
transform: "rotate(-23.7949 182.084 68.0816)",
fill: "#494E52"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M238.725 2.93094L260.368 17.2564L264.865 26.4556L181.615 99.0341L175.16 94.311L92.0028 110.947L85.3267 101.399L88.3269 73.8157L178.118 54.8553L238.725 2.93094ZM178.599 56.2622L89.6786 75.0388L86.9321 100.29C89.0979 99.8725 91.4124 99.4263 93.8446 98.9572C115.388 94.8019 146.171 88.8488 164.791 85.2026L165.415 85.0804C167.24 84.7228 168.943 84.3885 170.501 84.0816C175.853 83.0275 177.219 82.701 178.015 82.5107C178.07 82.4976 178.122 82.4852 178.173 82.4732C179.048 82.2652 181.558 81.5669 184.235 80.5851C186.742 79.6655 189.286 78.5354 190.802 77.3758L191.151 77.0922L191.644 76.6595C193.341 75.147 194.723 73.6739 195.61 71.871C196.571 69.916 196.982 67.5029 196.448 64.1178C195.8 60.0131 192.959 57.7574 189.408 56.6566C185.833 55.5483 181.637 55.6566 178.603 56.2615C178.601 56.2617 178.6 56.262 178.599 56.2622ZM192.631 77.7565L259.555 18.9531L263.042 26.0869L181.808 96.9078L178.132 89.5713L191.724 78.529C191.859 78.4249 191.988 78.32 192.11 78.2144L192.111 78.2136C192.286 78.0617 192.46 77.9094 192.631 77.7565ZM185.491 81.6908C185.24 81.7868 184.99 81.8802 184.743 81.9709C182.013 82.9723 179.447 83.6875 178.514 83.9093C178.463 83.9213 178.411 83.9338 178.356 83.9468C177.635 84.1192 176.472 84.3971 172.491 85.1919L177.172 88.4492L185.491 81.6908ZM176.631 89.8707L170.479 85.5903C169.306 85.8213 168.054 86.0673 166.731 86.3265L175.769 92.9276L179.548 95.6924L176.631 89.8707ZM164.758 86.7132C146.252 90.3362 116.027 96.1817 94.6324 100.308L93.2258 109.197L173.543 93.1293L164.758 86.7132ZM91.888 108.207L93.0909 100.606C91.0848 100.993 89.1642 101.363 87.3471 101.713L91.888 108.207ZM258.581 17.8436L197.306 71.6841C198.142 69.5779 198.41 67.0795 197.906 63.8876C197.143 59.0539 193.743 56.4549 189.845 55.2467C186.921 54.3402 183.662 54.1916 180.861 54.449L238.84 4.77668L258.581 17.8436ZM232.505 16.82L243.089 24.5643L205.915 56.5106L196.042 48.0665L232.505 16.82ZM232.118 19.096L198.312 48.0654L199.744 49.29L232.584 20.9424L232.118 19.096ZM233.456 22.1396L200.878 50.2604L205.913 54.5664L239.041 26.0969L233.456 22.1396ZM240.195 25.1054L240.717 24.6571L233.759 19.5663L234.06 20.7586L240.195 25.1054Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M190.194 69.9744C191.32 68.1409 191.576 66.2271 190.942 64.5937C190.308 62.9603 188.829 61.7198 186.761 61.1254C184.691 60.5307 182.116 60.6196 179.553 61.6139C176.991 62.6081 175.029 64.2794 173.902 66.1141C172.776 67.9477 172.52 69.8614 173.154 71.4948C173.788 73.1282 175.267 74.3687 177.335 74.9631C179.405 75.5578 181.98 75.4689 184.543 74.4746C187.105 73.4804 189.067 71.8091 190.194 69.9744ZM185.077 75.8508C190.749 73.6502 193.991 68.3712 192.318 64.0598C190.645 59.7484 184.691 58.0372 179.019 60.2378C173.347 62.4383 170.105 67.7173 171.778 72.0287C173.451 76.3401 179.405 78.0513 185.077 75.8508Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M187.391 69.169C188.127 67.9713 188.266 66.7721 187.881 65.7812C187.497 64.7903 186.586 63.9984 185.235 63.6102C183.883 63.2216 182.173 63.2741 180.456 63.9404C178.738 64.6068 177.441 65.7208 176.705 66.9196C175.969 68.1172 175.83 69.3165 176.215 70.3074C176.599 71.2983 177.511 72.0901 178.861 72.4783C180.214 72.8669 181.923 72.8144 183.64 72.1481C185.358 71.4818 186.655 70.3678 187.391 69.169ZM184.174 73.5242C188.156 71.9795 190.432 68.2738 189.257 65.2473C188.083 62.2208 183.904 61.0196 179.922 62.5643C175.94 64.1091 173.665 67.8148 174.839 70.8412C176.013 73.8677 180.193 75.0689 184.174 73.5242Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M240.499 41.2441C239.744 40.3649 239.844 39.04 240.724 38.285L249.781 30.5067C250.66 29.7516 251.985 29.8523 252.74 30.7315V30.7315C253.495 31.6108 253.395 32.9356 252.516 33.6907L243.458 41.469C242.579 42.224 241.254 42.1234 240.499 41.2441V41.2441Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M250.743 31.6265L241.685 39.4048C241.424 39.6287 241.395 40.0217 241.619 40.2825C241.842 40.5433 242.235 40.5731 242.496 40.3492L251.554 32.5709C251.815 32.3469 251.845 31.954 251.621 31.6932C251.397 31.4324 251.004 31.4025 250.743 31.6265ZM240.724 38.285C239.844 39.04 239.744 40.3649 240.499 41.2441C241.254 42.1234 242.579 42.224 243.458 41.469L252.516 33.6907C253.395 32.9356 253.495 31.6108 252.74 30.7315C251.985 29.8523 250.66 29.7516 249.781 30.5067L240.724 38.285Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M205.779 71.4647C205.005 70.5642 205.108 69.2073 206.009 68.4339L214.989 60.7218C215.89 59.9485 217.247 60.0516 218.02 60.9521V60.9521C218.793 61.8526 218.69 63.2095 217.79 63.9829L208.809 71.695C207.909 72.4683 206.552 72.3652 205.779 71.4647V71.4647Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M215.951 61.8416L206.97 69.5537C206.688 69.796 206.656 70.221 206.898 70.5031C207.141 70.7851 207.566 70.8174 207.848 70.5752L216.828 62.863C217.11 62.6208 217.143 62.1958 216.9 61.9137C216.658 61.6317 216.233 61.5994 215.951 61.8416ZM206.009 68.4339C205.108 69.2073 205.005 70.5642 205.779 71.4647C206.552 72.3652 207.909 72.4683 208.809 71.695L217.79 63.9829C218.69 63.2095 218.793 61.8526 218.02 60.9521C217.247 60.0516 215.89 59.9485 214.989 60.7218L206.009 68.4339Z",
fill: "black"
}),
(0, _jsxRuntime.jsx)("circle", {
cx: "141.356",
cy: "19.525",
r: "10.1855",
fill: "#FE89B4"
}),
(0, _jsxRuntime.jsx)("ellipse", {
cx: "139.062",
cy: "14.7094",
rx: "2.42519",
ry: "1.94015",
transform: "rotate(-34.544 139.062 14.7094)",
fill: "#FDF7FF"
}),
(0, _jsxRuntime.jsx)("circle", {
cx: "252.489",
cy: "79.7577",
r: "7.78893",
fill: "#EC5236"
}),
(0, _jsxRuntime.jsx)("ellipse", {
cx: "250.434",
cy: "76.3701",
rx: "2.61272",
ry: "2.09018",
transform: "rotate(-34.544 250.434 76.3701)",
fill: "#EDB69D"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M100.436 79.9254C100.461 79.6567 100.732 79.3897 101.042 79.329L106.657 78.2299C107.587 78.0478 108.281 78.5536 108.207 79.3596L107.759 84.2243C107.734 84.493 107.463 84.76 107.153 84.8207L100.416 86.1396C100.106 86.2003 99.8742 86.0317 99.899 85.7631L100.436 79.9254Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M95.8553 81.7775C95.9294 80.9715 96.7437 80.1704 97.6739 79.9883L98.7968 79.7685C99.1069 79.7078 99.3382 79.8764 99.3135 80.1451L99.1344 82.091C99.1096 82.3597 98.8382 82.6267 98.5282 82.6874L96.2824 83.127C95.9723 83.1877 95.741 83.0191 95.7657 82.7505L95.8553 81.7775Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M95.5865 84.6965C95.6112 84.4278 95.8826 84.1608 96.1927 84.1001L98.4385 83.6605C98.7486 83.5998 98.9799 83.7684 98.9552 84.037L98.7761 85.9829C98.7513 86.2516 98.4799 86.5186 98.1699 86.5793L95.9241 87.019C95.614 87.0797 95.3827 86.9111 95.4074 86.6424L95.5865 84.6965Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M95.2282 88.5884C95.2529 88.3197 95.5244 88.0527 95.8344 87.992L98.0802 87.5524C98.3903 87.4917 98.6216 87.6603 98.5969 87.929L98.4178 89.8749C98.3931 90.1435 98.1216 90.4105 97.8116 90.4712L96.6887 90.6911C95.7584 90.8732 95.0645 90.3674 95.1387 89.5614L95.2282 88.5884Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M99.7197 87.709C99.7444 87.4403 100.016 87.1733 100.326 87.1126L102.572 86.673C102.882 86.6123 103.113 86.7809 103.088 87.0496L102.909 88.9955C102.885 89.2641 102.613 89.5312 102.303 89.5919L100.057 90.0315C99.7472 90.0922 99.5159 89.9236 99.5406 89.6549L99.7197 87.709Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M104.211 86.8298C104.236 86.5611 104.507 86.2941 104.817 86.2334L107.063 85.7938C107.373 85.7331 107.605 85.9017 107.58 86.1704L107.49 87.1433C107.416 87.9493 106.602 88.7504 105.672 88.9325L104.549 89.1523C104.239 89.213 104.007 89.0444 104.032 88.7757L104.211 86.8298Z",
fill: "#B3AAAA"
}),
(0, _jsxRuntime.jsx)("defs", {
children: (0, _jsxRuntime.jsxs)("linearGradient", Object.assign({
id: "paint0_linear_3_672",
x1: "-44.5195",
y1: "122.42",
x2: "263.357",
y2: "-8.65023",
gradientUnits: "userSpaceOnUse"
}, {
children: [
(0, _jsxRuntime.jsx)("stop", {
offset: "0.110697",
stopColor: "#232323"
}),
(0, _jsxRuntime.jsx)("stop", {
offset: "1",
stopColor: "#3D3D3D"
})
]
}))
})
]
}));
};
const DEFAULT_DERIVATION_PATH = "44'/397'/0'/0'/1'";
const DerivationPath = ({ selector , options , onBack , onConnected , params , onError , onCloseModal })=>{
const [route, setRoute] = (0, _react.useState)("EnterDerivationPath");
const [derivationPath, setDerivationPath] = (0, _react.useState)(DEFAULT_DERIVATION_PATH);
const [customDerivationPath, setCustomDerivationPath] = (0, _react.useState)(1);
const [accounts, setAccounts] = (0, _react.useState)([]);
const [selectedAccounts, setSelectedAccounts] = (0, _react.useState)([]);
const [hardwareWallet, setHardwareWallet] = (0, _react.useState)();
const [customAccountId, setCustomAccountId] = (0, _react.useState)("");
const [connecting, setConnecting] = (0, _react.useState)(false);
const [headerTitle, setHeaderTitle] = (0, _react.useState)("Connect with Ledger");
const getAccountIds = (publicKey)=>__awaiter(void 0, void 0, void 0, function*() {
const response = yield fetch(`${selector.options.network.indexerUrl}/publicKey/ed25519:${publicKey}/accounts`);
if (!response.ok) throw new Error("Failed to get account id from public key");
const accountIds = yield response.json();
if (!Array.isArray(accountIds) || !accountIds.length) return [];
return accountIds;
});
const resolveAccounts = (wallet)=>__awaiter(void 0, void 0, void 0, function*() {
const publicKey = yield wallet.getPublicKey(derivationPath);
try {
const accountIds = yield getAccountIds(publicKey);
return accountIds.map((accountId, index)=>{
return {
derivationPath,
publicKey,
accountId,
selected: index === 0
};
});
} catch (e) {
return null;
}
});
const handleValidateAccount = ()=>__awaiter(void 0, void 0, void 0, function*() {
const wallet = yield selector.wallet(params.walletId);
if (wallet.type !== "hardware") return;
setConnecting(true);
setHardwareWallet(wallet);
try {
const resolvedAccounts = yield resolveAccounts(wallet);
if (!resolvedAccounts) {
setRoute("AddCustomAccountId");
return;
}
const noAccounts = resolvedAccounts.length === 0;
const multipleAccounts = resolvedAccounts.length > 1;
if (noAccounts) {
setHeaderTitle("No Accounts Found");
setRoute("NoAccountsFound");
return;
}
setAccounts(resolvedAccounts);
if (!multipleAccounts) setRoute("OverviewAccounts");
else {
setHeaderTitle("Select Your Accounts");
setRoute("ChooseAccount");
}
} catch (err) {
setConnecting(false);
const message = err instanceof Error ? err.message : "Something went wrong";
onError(message, wallet);
} finally{
setConnecting(false);
}
});
const handleAddCustomAccountId = ()=>__awaiter(void 0, void 0, void 0, function*() {
try {
setConnecting(true);
const publicKey = yield hardwareWallet.getPublicKey(derivationPath);
const accountList = [
{
derivationPath: derivationPath,
publicKey,
accountId: customAccountId,
selected: true
}
];
setAccounts(accountList);
setSelectedAccounts(accountList);
setHeaderTitle("Connecting 1 Account");
setRoute("OverviewAccounts");
} catch (err) {
setConnecting(false);
const message = err instanceof Error ? err.message : "Something went wrong";
onError(message, hardwareWallet);
} finally{
setConnecting(false);
}
});
const handleSignIn = ()=>{
const mapAccounts = selectedAccounts.map((account)=>{
return {
derivationPath: account.derivationPath,
publicKey: account.publicKey,
accountId: account.accountId
};
});
return hardwareWallet.signIn({
contractId: options.contractId,
methodNames: options.methodNames,
accounts: mapAccounts
}).then(()=>onConnected()).catch((err)=>{
onError(`Error: ${err.message}`, hardwareWallet);
});
};
const handleOnBackButtonClick = ()=>{
if (route === "SpecifyHDPath" || route === "NoAccountsFound" || route === "ChooseAccount") {
setHeaderTitle("Connect with Ledger");
setRoute("EnterDerivationPath");
}
if (route === "OverviewAccounts") {
setHeaderTitle("Select Your Accounts");
setRoute("ChooseAccount");
}
};
if (connecting) return (0, _jsxRuntime.jsx)("div", Object.assign({
className: "derivation-path-wrapper"
}, {
children: (0, _jsxRuntime.jsx)(WalletConnecting, {
wallet: hardwareWallet,
onBack: ()=>{
setConnecting(false);
},
onCloseModal: onCloseModal
})
}));
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header-wrapper"
}, {
children: [
(route === "SpecifyHDPath" || route === "NoAccountsFound" || route === "ChooseAccount" || route === "OverviewAccounts") && (0, _jsxRuntime.jsx)(BackArrow, {
onClick: handleOnBackButtonClick
}),
(0, _jsxRuntime.jsx)(ModalHeader, {
title: headerTitle,
onCloseModal: onCloseModal
})
]
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "derivation-path-wrapper"
}, {
children: [
route === "EnterDerivationPath" && (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "enter-derivation-path"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "ledger-image"
}, {
children: (0, _jsxRuntime.jsx)(LedgerDeviceIcon, {})
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "ledger-description"
}, {
children: [
(0, _jsxRuntime.jsx)("p", {
children: "Make sure your Ledger is connected securely, and that the NEAR app is open on your device."
}),
(0, _jsxRuntime.jsx)("p", Object.assign({
className: "specify-path",
onClick: ()=>{
setHeaderTitle("Specify HD Path");
setRoute("SpecifyHDPath");
}
}, {
children: "Specify HD Path"
}))
]
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: handleValidateAccount
}, {
children: "Continue"
}))
}))
]
})),
route === "SpecifyHDPath" && (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "specify-path-wrapper"
}, {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "change-path-wrapper"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "display-path"
}, {
children: (0, _jsxRuntime.jsx)("span", {
children: derivationPath.slice(0, -2)
})
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "change-path"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "path-value"
}, {
children: (0, _jsxRuntime.jsx)("span", {
children: customDerivationPath
})
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "buttons-wrapper"
}, {
children: [
(0, _jsxRuntime.jsx)("button", Object.assign({
onClick: ()=>{
const newValue = customDerivationPath + 1;
const path = derivationPath.slice(0, -2);
setDerivationPath(`${path}${newValue}'`);
setCustomDerivationPath(newValue);
}
}, {
children: (0, _jsxRuntime.jsx)("svg", Object.assign({
width: "10",
height: "7",
viewBox: "0 0 10 7",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: (0, _jsxRuntime.jsx)("path", {
d: "M9 5.4762L5 1.4762L1 5.4762",
stroke: "#4F7CD1",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
}))
})),
(0, _jsxRuntime.jsx)("button", Object.assign({
onClick: ()=>{
const newValue = customDerivationPath - 1;
if (newValue < 0) return;
const path = derivationPath.slice(0, -2);
setDerivationPath(`${path}${newValue}'`);
setCustomDerivationPath(newValue);
}
}, {
children: (0, _jsxRuntime.jsx)("svg", Object.assign({
width: "10",
height: "7",
viewBox: "0 0 10 7",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: (0, _jsxRuntime.jsx)("path", {
d: "M1 1.52382L5 5.52382L9 1.52382",
stroke: "#4F7CD1",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
}))
}))
]
}))
]
}))
]
})),
(0, _jsxRuntime.jsx)("p", Object.assign({
className: "path-description"
}, {
children: "Enter your preferred HD path, then scan for any active accounts."
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: handleValidateAccount
}, {
children: "Scan"
}))
}))
]
})),
route === "NoAccountsFound" && (0, _jsxRuntime.jsx)("div", Object.assign({
className: "no-accounts-found-wrapper"
}, {
children: (0, _jsxRuntime.jsxs)("p", {
children: [
"Can't found any account associated with this Ledger. Please create a new NEAR account on",
" ",
(0, _jsxRuntime.jsx)("a", Object.assign({
href: `https://${selector.options.network.networkId === "testnet" ? "testnet" : "app"}.mynearwallet.com/create`,
target: "_blank"
}, {
children: "MyNearWallet"
})),
" ",
"or connect an another Ledger."
]
})
})),
route === "ChooseAccount" && (0, _jsxRuntime.jsx)(HardwareWalletAccountsForm, {
accounts: accounts,
onSelectedChanged: (index, selected)=>{
setAccounts((prevAccounts)=>{
const updateAccounts = prevAccounts.map((account, idx)=>{
const selectedValue = index === idx ? selected : account.selected;
return Object.assign(Object.assign({}, account), {
selected: selectedValue
});
});
return [
...updateAccounts
];
});
},
onSubmit: (acc, e)=>{
e.preventDefault();
const selectedAcc = acc.filter((account)=>account.selected);
setSelectedAccounts(selectedAcc);
const numberOfAccounts = selectedAcc.length;
setHeaderTitle(`Connecting ${numberOfAccounts} Account${numberOfAccounts > 1 ? "s" : ""}`);
setRoute("OverviewAccounts");
},
onChangeRoute: (newRoute)=>{
if (newRoute === "SpecifyHDPath") setHeaderTitle("Specify HD Path");
setRoute(newRoute);
}
}),
route === "AddCustomAccountId" && (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "enter-custom-account"
}, {
children: [
(0, _jsxRuntime.jsx)("p", {
children: "Failed to automatically find account id. Provide it manually:"
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "input-wrapper"
}, {
children: (0, _jsxRuntime.jsx)("input", {
type: "text",
placeholder: "Account ID",
value: customAccountId,
onChange: (e)=>{
setCustomAccountId(e.target.value);
}
})
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: handleAddCustomAccountId
}, {
children: "Continue"
}))
}))
]
})),
route === "OverviewAccounts" && (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "overview-wrapper"
}, {
children: [
(0, _jsxRuntime.jsx)("p", {
children: "Overview the list of authorized account(s), complete sign in by clicking the button below."
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "accounts"
}, {
children: selectedAccounts.map((account, index)=>(0, _jsxRuntime.jsx)("div", {
children: (0, _jsxRuntime.jsx)("div", Object.assign({
className: "account"
}, {
children: (0, _jsxRuntime.jsx)("span", {
children: account.accountId
})
}))
}, account.accountId))
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: handleSignIn,
disabled: accounts.length === 0
}, {
children: "Finish"
}))
}))
]
}))
]
}))
]
});
};
const WalletNotInstalled = ({ module , onBack , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header-wrapper"
}, {
children: [
(0, _jsxRuntime.jsx)(BackArrow, {
onClick: onBack
}),
(0, _jsxRuntime.jsx)(ModalHeader, {
title: "",
onCloseModal: onCloseModal
})
]
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "wallet-not-installed-wrapper"
}, {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "wallet-data"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: `wallet-icon-box ${module.id}`
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: module.metadata.iconUrl,
alt: module.metadata.name
})
})),
(0, _jsxRuntime.jsx)("p", {
children: module.metadata.name
})
]
})),
(0, _jsxRuntime.jsxs)("p", {
children: [
`You'll need to install ${module.metadata.name} to continue. After installing`,
(0, _jsxRuntime.jsx)("span", Object.assign({
className: "refresh-link",
onClick: ()=>window.location.reload()
}, {
children: "\xa0refresh the page."
}))
]
}),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "action-buttons"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: ()=>{
if (module.type !== "injected") return;
window.open(module.metadata.downloadUrl, "_blank");
}
}, {
children: `Open ${module.metadata.name}`
}))
}))
]
}))
]
});
};
const WhatWallet = ({ title , description , icon })=>{
return (0, _jsxRuntime.jsx)("div", Object.assign({
className: "wallet-what"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content-side"
}, {
children: [
(0, _jsxRuntime.jsx)("h3", {
children: title
}),
(0, _jsxRuntime.jsx)("p", {
children: description
})
]
}))
}));
};
var img = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAA5ADkDAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+er/gsr/wWR/bW/a9/bd+P1rp/wAfPjB8MPgT8M/ix42+Hnwe+DfgL4geJfBPhTRPC/gLxFqvhbS/EWvaP4V1LS7PXvHniSOxn13Xtf1r+1tRsbnV7jQNJ1CLw9p+nWcQBF/wQn/aQ/aI8Wf8Fef2B/Dnin49fGjxL4e1f48aRaatoOv/ABS8cazo2qWjaLrjNa6jpeo67c2N7bsyqzQ3MEsZZVJXIFAH+wlQB/F1/wAHoPxO+JPwy/Zj/Ysvvht8QvHHw9vdU+O/j+01O88D+LNe8J3Wo2sPw/gmhtr640G/sJru3imJljhuHkjSQl1UNzQB/nmf8NZftT/9HL/tAf8Ah5fiL/8ANHQB/qRf8Gnnjjxp8Qv+CQ3g7xH4+8X+KPHHiGT48fG+0k17xf4g1bxLrMlpa61pi2tq+qa1d3t81vbKzLBC05jhViI1UE0Af0rUAFAH+Pb+0h/wQn/4K8+LP2iPj14p8OfsD/HjV/D3iX40fFLX9B1a00jRWtNU0bWfHGu6jpeo2rNris1ve2NzBcwsyqxjlUlQeKAPof8A4Ji/8Exf2+/2Bv2+/wBln9sf9sf9ln4ofs+fswfs+fFCw8f/ABo+NHj+w06z8G/DrwbZ6dqVjc+IfENzY6lf3cOnw3d/ZwO8FncSeZcRgRkEkAH+gZ/w/wCP+CNv/SQn4Af+DfXf/lDQB/Oj/wAHFnj/AMGf8Ft/gv8As5fC3/glB4hsP25/iF8EPif4q8f/ABY8KfBBpNU1XwL4N8Q+FIvDui+Idcj1mPRYotP1HW43023eGWdzcqVaNV+agD+TL/hwR/wWS/6R7ftAf+CfQ/8A5e0Af22f8EKP2vf2aP8AgkX+wJ4f/Y4/4KU/GPwh+x3+0/ovxQ+JXj/Vfgv8Xri707xlY+DfHWo2V94Q8Qz22lWerWg0/X7S1uJ7BxeGR44mLxocAgH7H/8AD/j/AII2/wDSQn4Af+DfXf8A5Q0AfYP/AA31+xv/ANHCfD//AMDL7/5BoA+vqAPyA/4L8f8AKG3/AIKE/wDZANX/APT7oNAH+MNQB/b5/wAGQ3/J0/7cH/Zv/wAPf/VizUAf6PlAH+UJ/wAHeP8AymS8a/8AZAPgT/6YtToA/mCoA/0AKAPrP4nf8HoP7Mfwy+JPxC+G19+xZ8d9Uvfh7448WeB7zU7Tx/8AD+G11G68J69f6DcX1tDNAZore7msHuIY5SZEjkVXO4GgDxfx/wD8HFnwX/4Lb+DPEP8AwSg+Fv7OXxP+CHxC/bnsG+CHhT4seP8AxV4U8Q+DfAuq6pJHrMeueIdF8OxR63qOnxRaLLC9vprrcl542U7VagD4w/4ghv2p/wDo+D9n/wD8N78Rf/j1AHt/wQ+CGq/8GfGq65+0j+0jrmn/ALYmiftiafb/AAQ8NeGvghb3PgXVfB2q+Bbn/hPLvXNcu/HnnWl/p9/aTCwt7ewAuY7kGWU+VgUAfSH/ABG8/ss/9GPfH/8A8OJ8Ov8A5HoA+T/i9/wSy8f/APB0j4zn/wCCr/wE+Kng/wDZZ+Hvi6wsPghb/Cf4vaNrXjHxlZ6r8GI20bU9cm1rwY0WiSafrUuopNYW8afabdI3W4JYigDzD/iCG/an/wCj4P2f/wDw3vxF/wDj1AH9IP8Aw5E+KX/RcPAH/hO+Iv8A45QB/lhftZf8nT/tL/8AZwHxl/8AVi+I6APv7/ggR/ymS/4J7f8AZwGj/wDpj12gD/Z6oA/iC/4Pef8Ak1n9h7/sv/xE/wDVdW9AH+cJQB/q9f8ABob/AMobfBf/AGcB8dv/AE+aVQB/T9QAUAfzU+OP+DTz/gkN8QvGni/x94j8HfHiTxD448UeIPF+vSWnxv1q1tJNZ8S6td61qj2tqumMttbtfXs7QwKzLDGVjBIXNAHyP+17/wAEKP2BP+CRf7NHxj/4KU/sceH/AIoaL+0/+x34QuPi98F9V8f/ABK1Hx14NsfGWnXdnpVtP4h8IX1la2mv6eLTVrwPYT3EUbyGNy2UAIB/Ml/xF4/8Fkv+h1+AH/hidC/+WdAH6nf8Esvi94z/AODpHx/8VPgJ/wAFX57Dxd8Pf2WfB+jfF74T2/wQsI/gxqtn4y8Y603gzWptc1PRm1GXWtPk0SJI7ewmSNLe5zcK5Y4oA/a//iEN/wCCNv8A0Jf7QH/h9tc/+VVAH8+P/BRr/go1+0v/AMG6X7S+qf8ABNb/AIJrap4Q8MfsweGPCHhP4vaVpXxe8J2nxX8ZJ4y+K9pPqvi+efxfqs9hdzafNd2FubCwNuI7GMMiMwYmgD4Q/wCIvH/gsl/0OvwA/wDDE6F/8s6AP6wf+HvH7ZH/AEGvh/8A+EJY/wDyXQB/V1QB+QH/AAX4/wCUNv8AwUJ/7IBq/wD6fdBoA/xhqAP7fP8AgyG/5On/AG4P+zf/AIe/+rFmoA/0fKAP8oT/AIO8f+UyXjX/ALIB8Cf/AExanQB/Pl+zh+zl8Y/2tPjX8P8A9n34CeCdY8f/ABR+JXiCx8P+HdC0izu7pYTd3EcV3rmt3Frb3C6N4X0C1eTVvEviG9RNN0LRrW81O/mitreRwAf6vn/DkDVf+i+af/4Rdz/8uaAP6DKAPkH9vr/kzf8AaE/7J/ef+l1jQB/GLQB+3v8AwRE/5Kl8cP8AsQPDv/qRSUAf0d0Afyi/8FeP+TyNa/7J/wCBP/SG7oA+r/8AgiB/yFPj7/14eCv/AEo1qgD+gugA/9k=";
const WalletHome = ({ selector , onCloseModal })=>{
const [modules, setModules] = (0, _react.useState)([]);
const [route, setRoute] = (0, _react.useState)("WalletInfo");
(0, _react.useEffect)(()=>{
const subscription = selector.store.observable.subscribe((state)=>{
const filteredModules = state.modules.slice(0, 3);
setModules(filteredModules);
});
return ()=>subscription.unsubscribe(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const goToWallet = (module)=>{
const { networkId } = selector.options.network;
let url = "";
if (module.type === "injected") url = module.metadata.downloadUrl;
// TODO: improve links to wallets other than injected type.
if (module.id === "my-near-wallet") {
const subdomain = networkId === "testnet" ? "testnet" : "app";
url = `https://${subdomain}.mynearwallet.com`;
}
if (module.id === "near-wallet") {
const subdomain1 = networkId === "testnet" ? "testnet." : "";
url = `https://wallet.${subdomain1}near.org`;
}
if (url === "" && module.type === "bridge" || module.type === "hardware") return;
window.open(url, "_blank");
};
return (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "wallet-home-wrapper"
}, {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header-wrapper"
}, {
children: [
route === "GetWallets" && (0, _jsxRuntime.jsx)(BackArrow, {
onClick: ()=>{
setRoute("WalletInfo");
}
}),
(0, _jsxRuntime.jsx)(ModalHeader, {
title: route === "GetWallets" ? "Get a Wallet" : "What is a Wallet?",
onCloseModal: onCloseModal
})
]
})),
route === "GetWallets" && (0, _jsxRuntime.jsx)("div", Object.assign({
className: "get-wallet-wrapper"
}, {
children: modules.map((module)=>{
const { iconUrl , name , description } = module.metadata;
return (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "single-wallet-get"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "icon"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: iconUrl,
alt: name
})
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "title"
}, {
children: name
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "description"
}, {
children: description
}))
]
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "button-get"
}, {
children: (0, _jsxRuntime.jsx)("button", Object.assign({
className: "get-wallet",
onClick: ()=>{
goToWallet(module);
}
}, {
children: "Get"
}))
}))
]
}), module.id);
})
})),
route === "WalletInfo" && (0, _jsxRuntime.jsxs)((0, _jsxRuntime.Fragment), {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "wallet-info-wrapper what-wallet-hide"
}, {
children: [
(0, _jsxRuntime.jsx)(WhatWallet, {
title: "Secure & Manage Your Digital Assets",
description: "Safely store and transfer your crypto and NFTs.",
icon: img
}),
(0, _jsxRuntime.jsx)(WhatWallet, {
title: "Log In to Any NEAR App",
description: "No need to create new accounts or credentials. Connect your wallet and you are good to go!",
icon: img
}),
(0, _jsxRuntime.jsx)("div", {
className: "button-spacing"
}),
(0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: ()=>{
setRoute("GetWallets");
}
}, {
children: "Get a Wallet"
}))
]
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "what-wallet-mobile"
}, {
children: [
(0, _jsxRuntime.jsx)("p", {
children: "Use a wallet to secure and manage your NEAR assets, and to log in to any NEAR app without the need for usernames and passwords."
}),
(0, _jsxRuntime.jsx)("button", Object.assign({
className: "middleButton",
onClick: ()=>{
setRoute("GetWallets");
}
}, {
children: "Get a Wallet"
}))
]
}))
]
})
]
}));
};
const WalletConnected = ({ module , onCloseModal })=>{
return (0, _jsxRuntime.jsxs)((0, _react.Fragment), {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-header"
}, {
children: [
(0, _jsxRuntime.jsx)("div", {
children: (0, _jsxRuntime.jsx)("span", Object.assign({
className: "connected-flag"
}, {
children: "Connected"
}))
}),
(0, _jsxRuntime.jsx)(CloseButton, {
onClick: onCloseModal
})
]
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "connecting-wrapper"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "content"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "icon"
}, {
children: (0, _jsxRuntime.jsx)("img", {
src: module === null || module === void 0 ? void 0 : module.metadata.iconUrl,
alt: module === null || module === void 0 ? void 0 : module.metadata.name
})
})),
(0, _jsxRuntime.jsx)("h3", Object.assign({
className: "connecting-name"
}, {
children: module === null || module === void 0 ? void 0 : module.metadata.name
})),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "wallet-connected-success"
}, {
children: [
(0, _jsxRuntime.jsxs)("svg", Object.assign({
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, {
children: [
(0, _jsxRuntime.jsx)("rect", {
width: "24",
height: "24",
rx: "12",
fill: "#51BD7C"
}),
(0, _jsxRuntime.jsx)("path", {
d: "M7.75 12.75L10 15.25L16.25 8.75",
stroke: "currentColor",
strokeWidth: "1.5",
strokeLinecap: "round",
strokeLinejoin: "round"
})
]
})),
(0, _jsxRuntime.jsx)("span", {
children: "Connection Successful"
})
]
}))
]
}))
}))
]
});
};
const getThemeClass = (theme)=>{
switch(theme){
case "dark":
return "dark-theme";
case "light":
return "light-theme";
default:
return "";
}
};
const Modal = ({ selector , options , visible , hide })=>{
var _a, _b, _c;
const [route, setRoute] = (0, _react.useState)({
name: "WalletHome"
});
const [alertMessage, setAlertMessage] = (0, _react.useState)(null);
const [selectedWallet, setSelectedWallet] = (0, _react.useState)();
(0, _react.useEffect)(()=>{
setRoute({
name: "WalletHome"
});
const { selectedWalletId , modules } = selector.store.getState();
if (selectedWalletId) {
const module = modules.find((m)=>m.id === selectedWalletId);
setSelectedWallet(module);
setRoute({
name: "WalletConnected",
params: {
module
}
});
}
}, [
visible
]);
(0, _react.useEffect)(()=>{
const subscription = selector.on("networkChanged", ({ networkId })=>{
// Switched back to the correct network.
if (networkId === selector.options.network.networkId) return handleDismissClick();
setRoute({
name: "WalletNetworkChanged"
});
});
return ()=>subscription.remove(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleDismissClick = (0, _react.useCallback)(()=>{
setAlertMessage(null);
setRoute({
name: "WalletHome"
});
hide();
}, [
hide
]);
(0, _react.useEffect)(()=>{
const close = (e)=>{
if (e.key === "Escape") handleDismissClick();
};
window.addEventListener("keydown", close);
return ()=>window.removeEventListener("keydown", close);
}, [
handleDismissClick
]);
const handleWalletClick = (module)=>__awaiter(void 0, void 0, void 0, function*() {
setSelectedWallet(module);
const { selectedWalletId } = selector.store.getState();
if (selectedWalletId === module.id) {
setRoute({
name: "WalletConnected",
params: {
module
}
});
return;
}
try {
const { deprecated , available } = module.metadata;
if (module.type === "injected" && !available) {
setRoute({
name: "WalletNotInstalled",
params: {
module: module
}
});
return;
}
const wallet = yield module.wallet();
if (deprecated) {
setAlertMessage(`${module.metadata.name} is deprecated. Please select another wallet.`);
setRoute({
name: "AlertMessage",
params: {
module: module
}
});
return;
}
setRoute({
name: "WalletConnecting",
params: {
wallet: wallet
}
});
if (wallet.type === "hardware") {
setRoute({
name: "DerivationPath",
params: {
walletId: wallet.id || "ledger"
}
});
return;
}
yield wallet.signIn({
contractId: options.contractId,
methodNames: options.methodNames
});
handleDismissClick();
} catch (err) {
const { name } = module.metadata;
const message = err instanceof Error ? err.message : "Something went wrong";
setAlertMessage(`Failed to sign in with ${name}: ${message}`);
setRoute({
name: "AlertMessage",
params: {
module: module
}
});
}
});
if (!visible) return null;
return (0, _jsxRuntime.jsxs)("div", Object.assign({
className: `nws-modal-wrapper ${getThemeClass(options === null || options === void 0 ? void 0 : options.theme)} ${visible ? "open" : ""}`
}, {
children: [
(0, _jsxRuntime.jsx)("div", {
className: "nws-modal-overlay",
onClick: handleDismissClick
}),
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal"
}, {
children: [
(0, _jsxRuntime.jsxs)("div", Object.assign({
className: "modal-left"
}, {
children: [
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "modal-left-title"
}, {
children: (0, _jsxRuntime.jsx)("h2", {
children: "Connect Your Wallet"
})
})),
(0, _jsxRuntime.jsx)(WalletOptions, {
handleWalletClick: handleWalletClick,
selector: selector
})
]
})),
(0, _jsxRuntime.jsx)("div", Object.assign({
className: "modal-right"
}, {
children: (0, _jsxRuntime.jsxs)("div", Object.assign({
className: "nws-modal-body"
}, {
children: [
route.name === "AlertMessage" && alertMessage && (0, _jsxRuntime.jsx)(AlertMessage, {
message: alertMessage,
module: (_a = route.params) === null || _a === void 0 ? void 0 : _a.module,
onBack: (retry)=>{
if (retry) handleWalletClick(selectedWallet);
setAlertMessage(null);
setRoute({
name: "WalletHome"
});
},
onCloseModal: handleDismissClick
}),
route.name === "DerivationPath" && (0, _jsxRuntime.jsx)(DerivationPath, {
selector: selector,
options: options,
onConnected: handleDismissClick,
params: route.params,
onBack: ()=>setRoute({
name: "WalletHome"
}),
onError: (message, wallet)=>{
const { modules } = selector.store.getState();
const findModule = modules.find((module)=>module.id === wallet.id);
setAlertMessage(message);
setRoute({
name: "AlertMessage",
params: {
module: findModule
}
});
},
onCloseModal: handleDismissClick
}),
route.name === "WalletNetworkChanged" && (0, _jsxRuntime.jsx)(WalletNetworkChanged, {
selector: selector,
onBack: ()=>setRoute({
name: "WalletHome"
}),
onCloseModal: handleDismissClick
}),
route.name === "WalletNotInstalled" && (0, _jsxRuntime.jsx)(WalletNotInstalled, {
module: (_b = route.params) === null || _b === void 0 ? void 0 : _b.module,
onBack: ()=>{
setRoute({
name: "WalletHome"
});
},
onCloseModal: handleDismissClick
}),
route.name === "WalletConnecting" && (0, _jsxRuntime.jsx)(WalletConnecting, {
wallet: (_c = route.params) === null || _c === void 0 ? void 0 : _c.wallet,
onBack: ()=>{
setRoute({
name: "WalletHome"
});
},
onCloseModal: handleDismissClick
}),
route.name === "WalletHome" && (0, _jsxRuntime.jsx)(WalletHome, {
selector: selector,
onCloseModal: handleDismissClick
}),
route.name === "WalletConnected" && (0, _jsxRuntime.jsx)(WalletConnected, {
module: selectedWallet,
onCloseModal: handleDismissClick
})
]
}))
}))
]
}))
]
}));
};
const MODAL_ELEMENT_ID = "near-wallet-selector-modal";
let modalInstance = null;
const setupModal = (selector, options)=>{
const el = document.createElement("div");
el.id = MODAL_ELEMENT_ID;
document.body.appendChild(el);
const container = document.getElementById(MODAL_ELEMENT_ID);
const root = (0, _client.createRoot)(container);
const render = (visible = false)=>{
root.render((0, _jsxRuntime.jsx)(Modal, {
selector: selector,
options: options,
visible: visible,
hide: ()=>render(false)
}));
};
render();
if (!modalInstance) modalInstance = {
show: ()=>{
render(true);
},
hide: ()=>{
render(false);
}
};
return modalInstance;
};
},{"react/jsx-runtime":"6AEwr","react-dom/client":"lOjBx","react":"21dqq","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}],"6AEwr":[function(require,module,exports) {
"use strict";
module.exports = require("./cjs/react-jsx-runtime.development.js");
},{"./cjs/react-jsx-runtime.development.js":"kujY4"}],"kujY4":[function(require,module,exports) {
/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
(function() {
"use strict";
var React = require("react");
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for("react.element");
var REACT_PORTAL_TYPE = Symbol.for("react.portal");
var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
var REACT_CONTEXT_TYPE = Symbol.for("react.context");
var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
var REACT_MEMO_TYPE = Symbol.for("react.memo");
var REACT_LAZY_TYPE = Symbol.for("react.lazy");
var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== "object") return null;
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === "function") return maybeIterator;
return null;
}
var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
function error(format) {
for(var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++)args[_key2 - 1] = arguments[_key2];
printWarning("error", format, args);
}
function printWarning(level, format, args) {
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== "") {
format += "%s";
args = args.concat([
stack
]);
} // eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat = args.map(function(item) {
return String(item);
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
// -----------------------------------------------------------------------------
var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing
var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.
var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
var REACT_MODULE_REFERENCE;
REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
function isValidElementType(type) {
if (typeof type === "string" || typeof type === "function") return true;
// Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) return true;
if (typeof type === "object" && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) return true;
}
return false;
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) return displayName;
var functionName = innerType.displayName || innerType.name || "";
return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || "Context";
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) // Host root, text node or just invalid type.
return null;
if (typeof type.tag === "number") error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
if (typeof type === "function") return type.displayName || type.name || null;
if (typeof type === "string") return type;
switch(type){
case REACT_FRAGMENT_TYPE:
return "Fragment";
case REACT_PORTAL_TYPE:
return "Portal";
case REACT_PROFILER_TYPE:
return "Profiler";
case REACT_STRICT_MODE_TYPE:
return "StrictMode";
case REACT_SUSPENSE_TYPE:
return "Suspense";
case REACT_SUSPENSE_LIST_TYPE:
return "SuspenseList";
}
if (typeof type === "object") switch(type.$$typeof){
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + ".Consumer";
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + ".Provider";
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, "ForwardRef");
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) return outerName;
return getComponentNameFromType(type.type) || "Memo";
case REACT_LAZY_TYPE:
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
return null;
}
var assign = Object.assign;
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */ prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */ }
disabledDepth++;
}
function reenableLogs() {
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */ var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */ }
if (disabledDepth < 0) error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
}
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
if (prefix === undefined) // Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || "";
}
// We use the prefix to ensure our stacks line up with native stack frames.
return "\n" + prefix + name;
}
var reentry = false;
var componentFrameCache;
var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if (!fn || reentry) return "";
var frame = componentFrameCache.get(fn);
if (frame !== undefined) return frame;
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current = null;
disableLogs();
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function() {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, "props", {
set: function() {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === "object" && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x1) {
control = x1;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x2) {
control = x2;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === "string") {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split("\n");
var controlLines = control.stack.split("\n");
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while(s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c])// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
for(; s >= 1 && c >= 0; s--, c--)// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "<anonymous>"
// but we have a user-provided "displayName"
// splice it in to make the stack more readable.
if (fn.displayName && _frame.includes("<anonymous>")) _frame = _frame.replace("<anonymous>", fn.displayName);
if (typeof fn === "function") componentFrameCache.set(fn, _frame);
return _frame;
}
}while (s >= 1 && c >= 0);
break;
}
}
} finally{
reentry = false;
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : "";
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
if (typeof fn === "function") componentFrameCache.set(fn, syntheticFrame);
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
return describeNativeComponentFrame(fn, false);
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) return "";
if (typeof type === "function") return describeNativeComponentFrame(type, shouldConstruct(type));
if (typeof type === "string") return describeBuiltInComponentFrame(type);
switch(type){
case REACT_SUSPENSE_TYPE:
return describeBuiltInComponentFrame("Suspense");
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame("SuspenseList");
}
if (typeof type === "object") switch(type.$$typeof){
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
return "";
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame.setExtraStackFrame(stack);
} else ReactDebugCurrentFrame.setExtraStackFrame(null);
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty);
for(var typeSpecName in typeSpecs)if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== "function") {
// eslint-disable-next-line react-internal/prod-error-codes
var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; " + "it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`." + "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
err.name = "Invariant Violation";
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error("Failed %s type: %s", location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
/*
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
*
* The functions in this module will throw an easier-to-understand,
* easier-to-debug exception with a clear errors message message explaining the
* problem. (Instead of a confusing exception thrown inside the implementation
* of the `value` object).
*/ // $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
return type;
} // $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value) {
try {
testStringCoercion(value);
return false;
} catch (e) {
return true;
}
}
function testStringCoercion(value) {
// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return "" + value;
}
function checkKeyStringCoercion(value) {
if (willCoercionThrow(value)) {
error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown;
var specialPropRefWarningShown;
var didWarnAboutStringRefs;
didWarnAboutStringRefs = {};
function hasValidRef(config) {
if (hasOwnProperty.call(config, "ref")) {
var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
if (getter && getter.isReactWarning) return false;
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if (hasOwnProperty.call(config, "key")) {
var getter = Object.getOwnPropertyDescriptor(config, "key").get;
if (getter && getter.isReactWarning) return false;
}
return config.key !== undefined;
}
function warnIfStringRefCannotBeAutoConverted(config, self) {
if (typeof config.ref === "string" && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function() {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, "key", {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function() {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, "ref", {
get: warnAboutAccessingRef,
configurable: true
});
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/ var ReactElement = function(type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, "validated", {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, "_self", {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, "_source", {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
return element;
};
/**
* https://github.com/reactjs/rfcs/pull/107
* @param {*} type
* @param {object} props
* @param {string} key
*/ function jsxDEV(type, config, maybeKey, source, self) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null; // Currently, key can be spread in as a prop. This causes a potential
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
// but as an intermediary step, we will use jsxDEV for everything except
// <div {...props} key="Hi" />, because we aren't currently able to tell if
// key is explicitly declared to be undefined or not.
if (maybeKey !== undefined) {
checkKeyStringCoercion(maybeKey);
key = "" + maybeKey;
}
if (hasValidKey(config)) {
checkKeyStringCoercion(config.key);
key = "" + config.key;
}
if (hasValidRef(config)) {
ref = config.ref;
warnIfStringRefCannotBeAutoConverted(config, self);
} // Remaining properties are added to a new props object
for(propName in config)if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) props[propName] = config[propName];
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for(propName in defaultProps)if (props[propName] === undefined) props[propName] = defaultProps[propName];
}
if (key || ref) {
var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
if (key) defineKeyPropWarningGetter(props, displayName);
if (ref) defineRefPropWarningGetter(props, displayName);
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement$1(element) {
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
var propTypesMisspellWarningShown;
propTypesMisspellWarningShown = false;
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/ function isValidElement(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner$1.current) {
var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
if (name) return "\n\nCheck the render method of `" + name + "`.";
}
return "";
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, "");
var lineNumber = source.lineNumber;
return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
}
return "";
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/ var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
if (parentName) info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/ function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) return;
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) return;
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = "";
if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) // Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/ function validateChildKeys(node, parentType) {
if (typeof node !== "object") return;
if (isArray(node)) for(var i = 0; i < node.length; i++){
var child = node[i];
if (isValidElement(child)) validateExplicitKey(child, parentType);
}
else if (isValidElement(node)) // This element was passed in a valid location.
{
if (node._store) node._store.validated = true;
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === "function") // Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
{
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while(!(step = iterator.next()).done)if (isValidElement(step.value)) validateExplicitKey(step.value, parentType);
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/ function validatePropTypes(element) {
var type = element.type;
if (type === null || type === undefined || typeof type === "string") return;
var propTypes;
if (typeof type === "function") propTypes = type.propTypes;
else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) propTypes = type.propTypes;
else return;
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, "prop", name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
}
if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/ function validateFragmentProps(fragment) {
var keys = Object.keys(fragment.props);
for(var i = 0; i < keys.length; i++){
var key = keys[i];
if (key !== "children" && key !== "key") {
setCurrentlyValidatingElement$1(fragment);
error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error("Invalid attribute `ref` supplied to `React.Fragment`.");
setCurrentlyValidatingElement$1(null);
}
}
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = "";
if (type === undefined || typeof type === "object" && type !== null && Object.keys(type).length === 0) info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
var sourceInfo = getSourceInfoErrorAddendum(source);
if (sourceInfo) info += sourceInfo;
else info += getDeclarationErrorAddendum();
var typeString;
if (type === null) typeString = "null";
else if (isArray(type)) typeString = "array";
else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
info = " Did you accidentally export a JSX literal instead of a component?";
} else typeString = typeof type;
error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
}
var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) return element;
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
var children = props.children;
if (children !== undefined) {
if (isStaticChildren) {
if (isArray(children)) {
for(var i = 0; i < children.length; i++)validateChildKeys(children[i], type);
if (Object.freeze) Object.freeze(children);
} else error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
} else validateChildKeys(children, type);
}
}
if (type === REACT_FRAGMENT_TYPE) validateFragmentProps(element);
else validatePropTypes(element);
return element;
} // These two functions exist to still get child warnings in dev
// even with the prod transform. This means that jsxDEV is purely
// opt-in behavior for better messages but that we won't stop
// giving you warnings if you use production apis.
function jsxWithValidationStatic(type, props, key) {
return jsxWithValidation(type, props, key, true);
}
function jsxWithValidationDynamic(type, props, key) {
return jsxWithValidation(type, props, key, false);
}
var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children.
// for now we can ship identical prod functions
var jsxs = jsxWithValidationStatic;
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.jsx = jsx;
exports.jsxs = jsxs;
})();
},{"react":"21dqq"}],"21dqq":[function(require,module,exports) {
"use strict";
module.exports = require("./cjs/react.development.js");
},{"./cjs/react.development.js":"6YvXz"}],"6YvXz":[function(require,module,exports) {
/**
* @license React
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
(function() {
"use strict";
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
var ReactVersion = "18.2.0";
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for("react.element");
var REACT_PORTAL_TYPE = Symbol.for("react.portal");
var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
var REACT_CONTEXT_TYPE = Symbol.for("react.context");
var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
var REACT_MEMO_TYPE = Symbol.for("react.memo");
var REACT_LAZY_TYPE = Symbol.for("react.lazy");
var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== "object") return null;
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === "function") return maybeIterator;
return null;
}
/**
* Keeps track of the current dispatcher.
*/ var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/ current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/ var ReactCurrentBatchConfig = {
transition: null
};
var ReactCurrentActQueue = {
current: null,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/ var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/ current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
currentExtraStackFrame = stack;
}
ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
currentExtraStackFrame = stack;
}; // Stack implementation injected b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment