@neardefi/shade-agent-js
Version:
This library is intended to be used in conjunction with the [shade agent template](https://github.com/NearDeFi/shade-agent-template/).
4,331 lines • 145 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// node_modules/mustache/mustache.js
var require_mustache = __commonJS({
"node_modules/mustache/mustache.js"(exports2, module2) {
(function(global, factory) {
typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = global || self, global.Mustache = factory());
})(exports2, function() {
"use strict";
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";
}
function typeStr(obj) {
return isArray(obj) ? "array" : typeof obj;
}
function escapeRegExp(string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function hasProperty(obj, propName) {
return obj != null && typeof obj === "object" && propName in obj;
}
function primitiveHasOwnProperty(primitive, propName) {
return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName);
}
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 = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
"`": "`",
"=": "="
};
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 = /#|\^|\/|>|\{|&|=|!/;
function parseTemplate(template, tags) {
if (!template)
return [];
var lineHasNonSpace = false;
var sections = [];
var tokens = [];
var spaces = [];
var hasTag = false;
var nonSpace = false;
var indentation = "";
var tagIndex = 0;
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;
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;
if (chr === "\n") {
stripSpace();
indentation = "";
tagIndex = 0;
lineHasNonSpace = false;
}
}
}
if (!scanner.scan(openingTagRe))
break;
hasTag = true;
type = scanner.scan(tagRe) || "name";
scanner.scan(whiteRe);
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);
}
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 === "/") {
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 === "=") {
compileTags(value);
}
}
stripSpace();
openSection = sections.pop();
if (openSection)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
return nestTokens(squashTokens(tokens));
}
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;
}
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;
}
function Scanner(string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
Scanner.prototype.eos = function eos() {
return this.tail === "";
};
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;
};
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;
};
function Context(view, parentContext) {
this.view = view;
this.cache = { ".": this.view };
this.parent = parentContext;
}
Context.prototype.push = function push(view) {
return new Context(view, this);
};
Context.prototype.lookup = function lookup(name) {
var cache = this.cache;
var value;
if (cache.hasOwnProperty(name)) {
value = cache[name];
} else {
var context = this, intermediateValue, names, index, lookupHit = false;
while (context) {
if (name.indexOf(".") > 0) {
intermediateValue = context.view;
names = name.split(".");
index = 0;
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];
lookupHit = hasProperty(context.view, name);
}
if (lookupHit) {
value = intermediateValue;
break;
}
context = context.parent;
}
cache[name] = value;
}
if (isFunction(value))
value = value.call(this.view);
return value;
};
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 = {};
}
};
}
Writer.prototype.clearCache = function clearCache() {
if (typeof this.templateCache !== "undefined") {
this.templateCache.clear();
}
};
Writer.prototype.parse = function parse(template, tags) {
var cache = this.templateCache;
var cacheKey = template + ":" + (tags || mustache.tags).join(":");
var isCacheEnabled = typeof cache !== "undefined";
var tokens = isCacheEnabled ? cache.get(cacheKey) : void 0;
if (tokens == void 0) {
tokens = parseTemplate(template, tags);
isCacheEnabled && cache.set(cacheKey, tokens);
}
return tokens;
};
Writer.prototype.render = function render(template, view, partials, tags) {
var tokens = this.parse(template, tags);
var context = view instanceof Context ? view : new Context(view, void 0);
return this.renderTokens(tokens, context, partials, template, tags);
};
Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, tags) {
var buffer = "";
var token, symbol, value;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
value = void 0;
token = tokens[i];
symbol = token[0];
if (symbol === "#") value = this.renderSection(token, context, partials, originalTemplate);
else if (symbol === "^") value = this.renderInverted(token, context, partials, originalTemplate);
else if (symbol === ">") value = this.renderPartial(token, context, partials, tags);
else if (symbol === "&") value = this.unescapedValue(token, context);
else if (symbol === "name") value = this.escapedValue(token, context);
else if (symbol === "text") value = this.rawValue(token);
if (value !== void 0)
buffer += value;
}
return buffer;
};
Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate) {
var self2 = this;
var buffer = "";
var value = context.lookup(token[1]);
function subRender(template) {
return self2.render(template, context, partials);
}
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);
}
} else if (typeof value === "object" || typeof value === "string" || typeof value === "number") {
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
} else if (isFunction(value)) {
if (typeof originalTemplate !== "string")
throw new Error("Cannot use higher-order sections without the original template");
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);
}
return buffer;
};
Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate) {
var value = context.lookup(token[1]);
if (!value || isArray(value) && value.length === 0)
return this.renderTokens(token[4], context, partials, originalTemplate);
};
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, tags) {
if (!partials) return;
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);
}
return this.renderTokens(this.parse(indentedValue, tags), context, partials, indentedValue);
}
};
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) {
var value = context.lookup(token[1]);
if (value != null)
return mustache.escape(value);
};
Writer.prototype.rawValue = function rawValue(token) {
return token[1];
};
var mustache = {
name: "mustache.js",
version: "4.0.0",
tags: ["{{", "}}"],
clearCache: void 0,
escape: void 0,
parse: void 0,
render: void 0,
Scanner: void 0,
Context: void 0,
Writer: void 0,
/**
* 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;
}
};
var defaultWriter = new Writer();
mustache.clearCache = function clearCache() {
return defaultWriter.clearCache();
};
mustache.parse = function parse(template, tags) {
return defaultWriter.parse(template, tags);
};
mustache.render = function render(template, view, partials, tags) {
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, tags);
};
mustache.escape = escapeHtml;
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;
return mustache;
});
}
});
// node_modules/depd/index.js
var require_depd = __commonJS({
"node_modules/depd/index.js"(exports2, module2) {
var relative = require("path").relative;
module2.exports = depd2;
var basePath = process.cwd();
function containsNamespace(str, namespace) {
var vals = str.split(/[ ,]+/);
var ns = String(namespace).toLowerCase();
for (var i = 0; i < vals.length; i++) {
var val = vals[i];
if (val && (val === "*" || val.toLowerCase() === ns)) {
return true;
}
}
return false;
}
function convertDataDescriptorToAccessor(obj, prop, message) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
var value = descriptor.value;
descriptor.get = function getter() {
return value;
};
if (descriptor.writable) {
descriptor.set = function setter(val) {
return value = val;
};
}
delete descriptor.value;
delete descriptor.writable;
Object.defineProperty(obj, prop, descriptor);
return descriptor;
}
function createArgumentsString(arity) {
var str = "";
for (var i = 0; i < arity; i++) {
str += ", arg" + i;
}
return str.substr(2);
}
function createStackString(stack) {
var str = this.name + ": " + this.namespace;
if (this.message) {
str += " deprecated " + this.message;
}
for (var i = 0; i < stack.length; i++) {
str += "\n at " + stack[i].toString();
}
return str;
}
function depd2(namespace) {
if (!namespace) {
throw new TypeError("argument namespace is required");
}
var stack = getStack();
var site = callSiteLocation(stack[1]);
var file = site[0];
function deprecate(message) {
log.call(deprecate, message);
}
deprecate._file = file;
deprecate._ignored = isignored(namespace);
deprecate._namespace = namespace;
deprecate._traced = istraced(namespace);
deprecate._warned = /* @__PURE__ */ Object.create(null);
deprecate.function = wrapfunction;
deprecate.property = wrapproperty;
return deprecate;
}
function eehaslisteners(emitter, type) {
var count = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
return count > 0;
}
function isignored(namespace) {
if (process.noDeprecation) {
return true;
}
var str = process.env.NO_DEPRECATION || "";
return containsNamespace(str, namespace);
}
function istraced(namespace) {
if (process.traceDeprecation) {
return true;
}
var str = process.env.TRACE_DEPRECATION || "";
return containsNamespace(str, namespace);
}
function log(message, site) {
var haslisteners = eehaslisteners(process, "deprecation");
if (!haslisteners && this._ignored) {
return;
}
var caller;
var callFile;
var callSite;
var depSite;
var i = 0;
var seen = false;
var stack = getStack();
var file = this._file;
if (site) {
depSite = site;
callSite = callSiteLocation(stack[1]);
callSite.name = depSite.name;
file = callSite[0];
} else {
i = 2;
depSite = callSiteLocation(stack[i]);
callSite = depSite;
}
for (; i < stack.length; i++) {
caller = callSiteLocation(stack[i]);
callFile = caller[0];
if (callFile === file) {
seen = true;
} else if (callFile === this._file) {
file = this._file;
} else if (seen) {
break;
}
}
var key = caller ? depSite.join(":") + "__" + caller.join(":") : void 0;
if (key !== void 0 && key in this._warned) {
return;
}
this._warned[key] = true;
var msg = message;
if (!msg) {
msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite);
}
if (haslisteners) {
var err = DeprecationError(this._namespace, msg, stack.slice(i));
process.emit("deprecation", err);
return;
}
var format = process.stderr.isTTY ? formatColor : formatPlain;
var output = format.call(this, msg, caller, stack.slice(i));
process.stderr.write(output + "\n", "utf8");
}
function callSiteLocation(callSite) {
var file = callSite.getFileName() || "<anonymous>";
var line = callSite.getLineNumber();
var colm = callSite.getColumnNumber();
if (callSite.isEval()) {
file = callSite.getEvalOrigin() + ", " + file;
}
var site = [file, line, colm];
site.callSite = callSite;
site.name = callSite.getFunctionName();
return site;
}
function defaultMessage(site) {
var callSite = site.callSite;
var funcName = site.name;
if (!funcName) {
funcName = "<anonymous@" + formatLocation(site) + ">";
}
var context = callSite.getThis();
var typeName = context && callSite.getTypeName();
if (typeName === "Object") {
typeName = void 0;
}
if (typeName === "Function") {
typeName = context.name || typeName;
}
return typeName && callSite.getMethodName() ? typeName + "." + funcName : funcName;
}
function formatPlain(msg, caller, stack) {
var timestamp = (/* @__PURE__ */ new Date()).toUTCString();
var formatted = timestamp + " " + this._namespace + " deprecated " + msg;
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += "\n at " + stack[i].toString();
}
return formatted;
}
if (caller) {
formatted += " at " + formatLocation(caller);
}
return formatted;
}
function formatColor(msg, caller, stack) {
var formatted = "\x1B[36;1m" + this._namespace + "\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m" + msg + "\x1B[39m";
if (this._traced) {
for (var i = 0; i < stack.length; i++) {
formatted += "\n \x1B[36mat " + stack[i].toString() + "\x1B[39m";
}
return formatted;
}
if (caller) {
formatted += " \x1B[36m" + formatLocation(caller) + "\x1B[39m";
}
return formatted;
}
function formatLocation(callSite) {
return relative(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2];
}
function getStack() {
var limit = Error.stackTraceLimit;
var obj = {};
var prep = Error.prepareStackTrace;
Error.prepareStackTrace = prepareObjectStackTrace;
Error.stackTraceLimit = Math.max(10, limit);
Error.captureStackTrace(obj);
var stack = obj.stack.slice(1);
Error.prepareStackTrace = prep;
Error.stackTraceLimit = limit;
return stack;
}
function prepareObjectStackTrace(obj, stack) {
return stack;
}
function wrapfunction(fn, message) {
if (typeof fn !== "function") {
throw new TypeError("argument fn must be a function");
}
var args = createArgumentsString(fn.length);
var stack = getStack();
var site = callSiteLocation(stack[1]);
site.name = fn.name;
var deprecatedfn = new Function(
"fn",
"log",
"deprecate",
"message",
"site",
'"use strict"\nreturn function (' + args + ") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}"
)(fn, log, this, message, site);
return deprecatedfn;
}
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");
}
var deprecate = this;
var stack = getStack();
var site = callSiteLocation(stack[1]);
site.name = prop;
if ("value" in descriptor) {
descriptor = convertDataDescriptorToAccessor(obj, prop, message);
}
var get = descriptor.get;
var set = descriptor.set;
if (typeof get === "function") {
descriptor.get = function getter() {
log.call(deprecate, message, site);
return get.apply(this, arguments);
};
}
if (typeof set === "function") {
descriptor.set = function setter() {
log.call(deprecate, message, site);
return set.apply(this, arguments);
};
}
Object.defineProperty(obj, prop, descriptor);
}
function DeprecationError(namespace, message, stack) {
var error = new Error();
var stackString;
Object.defineProperty(error, "constructor", {
value: DeprecationError
});
Object.defineProperty(error, "message", {
configurable: true,
enumerable: false,
value: message,
writable: true
});
Object.defineProperty(error, "name", {
enumerable: false,
configurable: true,
value: "DeprecationError",
writable: true
});
Object.defineProperty(error, "namespace", {
configurable: true,
enumerable: false,
value: namespace,
writable: true
});
Object.defineProperty(error, "stack", {
configurable: true,
enumerable: false,
get: function() {
if (stackString !== void 0) {
return stackString;
}
return stackString = createStackString.call(this, stack);
},
set: function setter(val) {
stackString = val;
}
});
return error;
}
}
});
// node_modules/exponential-backoff/dist/options.js
var require_options = __commonJS({
"node_modules/exponential-backoff/dist/options.js"(exports2) {
"use strict";
var __assign = exports2 && exports2.__assign || function() {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports2, "__esModule", { value: true });
var defaultOptions = {
delayFirstAttempt: false,
jitter: "none",
maxDelay: Infinity,
numOfAttempts: 10,
retry: function() {
return true;
},
startingDelay: 100,
timeMultiple: 2
};
function getSanitizedOptions(options) {
var sanitized = __assign(__assign({}, defaultOptions), options);
if (sanitized.numOfAttempts < 1) {
sanitized.numOfAttempts = 1;
}
return sanitized;
}
exports2.getSanitizedOptions = getSanitizedOptions;
}
});
// node_modules/exponential-backoff/dist/jitter/full/full.jitter.js
var require_full_jitter = __commonJS({
"node_modules/exponential-backoff/dist/jitter/full/full.jitter.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
function fullJitter(delay) {
var jitteredDelay = Math.random() * delay;
return Math.round(jitteredDelay);
}
exports2.fullJitter = fullJitter;
}
});
// node_modules/exponential-backoff/dist/jitter/no/no.jitter.js
var require_no_jitter = __commonJS({
"node_modules/exponential-backoff/dist/jitter/no/no.jitter.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
function noJitter(delay) {
return delay;
}
exports2.noJitter = noJitter;
}
});
// node_modules/exponential-backoff/dist/jitter/jitter.factory.js
var require_jitter_factory = __commonJS({
"node_modules/exponential-backoff/dist/jitter/jitter.factory.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
var full_jitter_1 = require_full_jitter();
var no_jitter_1 = require_no_jitter();
function JitterFactory(options) {
switch (options.jitter) {
case "full":
return full_jitter_1.fullJitter;
case "none":
default:
return no_jitter_1.noJitter;
}
}
exports2.JitterFactory = JitterFactory;
}
});
// node_modules/exponential-backoff/dist/delay/delay.base.js
var require_delay_base = __commonJS({
"node_modules/exponential-backoff/dist/delay/delay.base.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
var jitter_factory_1 = require_jitter_factory();
var Delay = (
/** @class */
function() {
function Delay2(options) {
this.options = options;
this.attempt = 0;
}
Delay2.prototype.apply = function() {
var _this = this;
return new Promise(function(resolve) {
return setTimeout(resolve, _this.jitteredDelay);
});
};
Delay2.prototype.setAttemptNumber = function(attempt) {
this.attempt = attempt;
};
Object.defineProperty(Delay2.prototype, "jitteredDelay", {
get: function() {
var jitter = jitter_factory_1.JitterFactory(this.options);
return jitter(this.delay);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Delay2.prototype, "delay", {
get: function() {
var constant = this.options.startingDelay;
var base = this.options.timeMultiple;
var power = this.numOfDelayedAttempts;
var delay = constant * Math.pow(base, power);
return Math.min(delay, this.options.maxDelay);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Delay2.prototype, "numOfDelayedAttempts", {
get: function() {
return this.attempt;
},
enumerable: true,
configurable: true
});
return Delay2;
}()
);
exports2.Delay = Delay;
}
});
// node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js
var require_skip_first_delay = __commonJS({
"node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js"(exports2) {
"use strict";
var __extends2 = exports2 && exports2.__extends || /* @__PURE__ */ function() {
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
};
return extendStatics(d, b);
};
return function(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = exports2 && exports2.__generator || function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
}, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports2, "__esModule", { value: true });
var delay_base_1 = require_delay_base();
var SkipFirstDelay = (
/** @class */
function(_super) {
__extends2(SkipFirstDelay2, _super);
function SkipFirstDelay2() {
return _super !== null && _super.apply(this, arguments) || this;
}
SkipFirstDelay2.prototype.apply = function() {
return __awaiter(this, void 0, void 0, function() {
return __generator(this, function(_a2) {
return [2, this.isFirstAttempt ? true : _super.prototype.apply.call(this)];
});
});
};
Object.defineProperty(SkipFirstDelay2.prototype, "isFirstAttempt", {
get: function() {
return this.attempt === 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SkipFirstDelay2.prototype, "numOfDelayedAttempts", {
get: function() {
return this.attempt - 1;
},
enumerable: true,
configurable: true
});
return SkipFirstDelay2;
}(delay_base_1.Delay)
);
exports2.SkipFirstDelay = SkipFirstDelay;
}
});
// node_modules/exponential-backoff/dist/delay/always/always.delay.js
var require_always_delay = __commonJS({
"node_modules/exponential-backoff/dist/delay/always/always.delay.js"(exports2) {
"use strict";
var __extends2 = exports2 && exports2.__extends || /* @__PURE__ */ function() {
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
};
return extendStatics(d, b);
};
return function(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
Object.defineProperty(exports2, "__esModule", { value: true });
var delay_base_1 = require_delay_base();
var AlwaysDelay = (
/** @class */
function(_super) {
__extends2(AlwaysDelay2, _super);
function AlwaysDelay2() {
return _super !== null && _super.apply(this, arguments) || this;
}
return AlwaysDelay2;
}(delay_base_1.Delay)
);
exports2.AlwaysDelay = AlwaysDelay;
}
});
// node_modules/exponential-backoff/dist/delay/delay.factory.js
var require_delay_factory = __commonJS({
"node_modules/exponential-backoff/dist/delay/delay.factory.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
var skip_first_delay_1 = require_skip_first_delay();
var always_delay_1 = require_always_delay();
function DelayFactory(options, attempt) {
var delay = initDelayClass(options);
delay.setAttemptNumber(attempt);
return delay;
}
exports2.DelayFactory = DelayFactory;
function initDelayClass(options) {
if (!options.delayFirstAttempt) {
return new skip_first_delay_1.SkipFirstDelay(options);
}
return new always_delay_1.AlwaysDelay(options);
}
}
});
// node_modules/exponential-backoff/dist/backoff.js
var require_backoff = __commonJS({
"node_modules/exponential-backoff/dist/backoff.js"(exports2) {
"use strict";
var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = exports2 && exports2.__generator || function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
}, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports2, "__esModule", { value: true });
var options_1 = require_options();
var delay_factory_1 = require_delay_factory();
function backOff2(request, options) {
if (options === void 0) {
options = {};
}
return __awaiter(this, void 0, void 0, function() {
var sanitizedOptions, backOff3;
return __generator(this, function(_a2) {
switch (_a2.label) {
case 0:
sanitizedOptions = options_1.getSanitizedOptions(options);
backOff3 = new BackOff(request, sanitizedOptions);
return [4, backOff3.execute()];
case 1:
return [2, _a2.sent()];
}
});
});
}
exports2.backOff = backOff2;
var BackOff = (
/** @class */
function() {
function BackOff2(request, options) {
this.request = request;
this.options = options;
this.attemptNumber = 0;
}
BackOff2.prototype.execute = function() {
return __awaiter(this, void 0, void 0, function() {
var e_1, shouldRetry;
return __generator(this, function(_a2) {
switch (_a2.label) {
case 0:
if (!!this.attemptLimitReached) return [3, 7];
_a2.label = 1;
case 1:
_a2.trys.push([1, 4, , 6]);
return [4, this.applyDelay()];
case 2:
_a2.sent();
return [4, this.request()];
case 3:
return [2, _a2.sent()];
case 4:
e_1 = _a2.sent();
this.attemptNumber++;
return [4, this.options.retry(e_1, this.attemptNumber)];
case 5:
shouldRetry = _a2.sent();
if (!shouldRetry || this.attemptLimitReached) {
throw e_1;
}
return [3, 6];
case 6:
return [3, 0];
case 7:
throw new Error("Something went wrong.");
}
});
});
};
Object.defineProperty(BackOff2.prototype, "attemptLimitReached", {
get: function() {
return this.attemptNumber >= this.options.numOfAttempts;
},
enumerable: true,
configurable: true
});
BackOff2.prototype.applyDelay = function() {
return __awaiter(this, void 0, void 0, function() {
var delay;
return __generator(this, function(_a2) {
switch (_a2.label) {
case 0:
delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber);
return [4, delay.apply()];
case 1:
_a2.sent();
return [
2
/*return*/
];
}
});
});
};
return BackOff2;
}()
);
}
});
// src/nearProvider.ts
var nearProvider_exports = {};
__export(nearProvider_exports, {
getProvider: () => getProvider
});
module.exports = __toCommonJS(nearProvider_exports);
// node_modules/@near-js/types/lib/esm/errors.js
var TypedError = class extends Error {
constructor(message, type, context) {
super(message);
__publicField(this, "type");
__publicField(this, "context");
this.type = type || "UntypedError";
this.context = context;
}
};
// node_modules/@near-js/utils/lib/esm/index.js
var import_mustache = __toESM(require_mustache(), 1);
// node_modules/@scure/base/lib/esm/index.js
function isBytes(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function isArrayOf(isString2, arr) {
if (!Array.isArray(arr))
return false;
if (arr.length === 0)
return true;
if (isString2) {
return arr.every((item) => typeof item === "string");
} else {
return arr.every((item) => Number.isSafeInteger(item));
}
}
function astr(label, input) {
if (typeof input !== "string")
throw new Error(`${label}: string expected`);
return true;
}
function anumber(n) {
if (!Number.isSafeInteger(n))
throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
if (!Array.isArray(input))
throw new Error("array expected");
}
function astrArr(label, input) {
if (!isArrayOf(true, input))
throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
if (!isArrayOf(false, input))
throw new Error(`${label}: array of numbers expected`);
}
// @__NO_SIDE_EFFECTS__
function chain(...args) {
const id = (a) => a;
const wrap = (a, b) => (c) => a(b(c));
const encode = args.map((x) => x.encode).reduceRight(wrap, id);
const decode = args.map((x) => x.decode).reduce(wrap, id);
return { encode, decode };
}
// @__NO_SIDE_EFFECTS__
function alphabet(letters) {
const lettersA = typeof letters === "string" ? letters.split("") : letters;
const len = lettersA.length;
astrArr("alphabet", lettersA);
const indexes = new Map(lettersA.map((l, i) => [l, i]));
return {
encode: (digits) => {
aArr(digits);
return digits.map((i) => {
if (!Number.isSafeInteger(i) || i < 0 || i >= len)
throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
return lettersA[i];
});
},
decode: (input) => {
aArr(input);
return input.map((letter) => {
astr("alphabet.decode", letter);
const i = indexes.get(letter);
if (i === void 0)
throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
return i;
});
}
};
}
// @__NO_SIDE_EFFECTS__
function join(separator = "") {
astr("join", separator);
return {
encode: (from) => {
astrArr("join.decode", from);
return from.join(separator);
},
decode: (to) => {
astr("join.decode", to);
return to.split(separator);
}
};
}
function convertRadix(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
aArr(data);
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data, (d) => {
anumber(d);
if (d < 0 || d >= from)
throw new Error(`invalid integer: ${d}`);
return d;
});
const dlen = digits.length;
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < dlen; i++) {
const digit = digits[i];
const fromCarry = from * carry;
const digitBase = fromCarry + digit;
if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
throw new Error("convertRadix: carry overflow");
}
const div = digitBase / to;
carry = digitBase % to;
const rounded = Math.floor(div);
digits[i] = rounded;
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!rounded)
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
// @__NO_SIDE_EFFECTS__
function radix(num) {
anumber(num);
const _256 = 2 ** 8;
return {
encode: (bytes) => {
if (!isBytes(bytes))
throw new Error("radix.encode input should be Uint8Array");
return convertRadix(Array.from(bytes), _256, num);
},
decode: (digits) => {
anumArr("radix.decode", digits);
return Uint8Array.from(convertRadix(digits, num, _256));
}
};
}
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join(""));
var base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
// node_modules/@near-js/utils/lib/esm/index.js
var import_depd = __toESM(require_depd(), 1);
var error_messages_default = {
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",
AccessKeyDoesNotExist: "Can't complete the action because access key {{public_key}} 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",
ShardCongested: "Shard {{shard_id}} rejected the transaction due to congestion level {{congestion_level}}, try again later",
ShardStuck: "Shard {{shard_id}} rejected the transaction because it missed {{missed_chunks}} chunks and needs to recover before accepting new transactions, try again later"
};
var ErrorMessages = error_messages_default;
var NEAR_NOMINATION_EXP = 24;
var NEAR_NOMINATION = 10n ** BigInt(NEAR_NOMINATION_EXP);
var ROUNDING_OFFSETS = [];
var BN10 = 10n;
for (let i = 0, offset = 5n; i < NEAR_NOMINATION_EXP; i++, offset = offset * BN10) {
ROUNDING_OFFSETS[i] = offset;
}
function formatNearAmount(balance, fracDigits = NEAR_NOMINATION_EXP) {
let balanceBN = BigInt(balance);
if (fracDigits !== NEAR_NOMINATION_EXP) {
const roundingExp = NEAR_NOMINATION_EXP - fracDigits - 1;
if (roundingExp > 0) {
balanceBN += ROUNDING_OFFSETS[roundingExp];
}
}
balance = balanceBN.toString();
const wholeStr = balance.substring(0, balance.length - NEAR_NOMINATION_EXP) || "0";
const fractionStr = balance.substring(balance.length - NEAR_NOMINATION_EXP).padStart(NEAR_NOMINATION_EXP, "0").substring(0, fracDigits);
return trimTrailingZeroes(`${formatWithCommas(wholeStr)}.${fractionStr}`);
}
function trimTrailingZeroes(value) {
return value.replace(/\.?0*$/, "");
}
function formatWithCommas(value) {
const pattern = /(-?\d+)(\d{3})/;
while (pattern.test(value)) {
value = value.replace(pattern, "$1,$2");
}
return value;
}
function baseEncode(value) {
if (typeof value === "string") {
const bytes = [];
for (let c = 0; c < value.length; c++) {
bytes.push(value.charCodeAt(c));
}
value = new Uint8Array(bytes);
}
return base58.encode(value);
}
var rpc_error_schema_default = {
schema: {
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",
"DeleteAccountWithLargeState",
"DelegateActionInvalidSignature",
"DelegateActionSenderDoesNotMatchTxReceiver",
"DelegateActionExpired",
"DelegateActionAccessKeyError",
"DelegateActionInvalidNonce",
"DelegateActionNonceTooLarge"
],
props: {
index: ""
}
},
ActionsValidationError: {
name: "ActionsValidationError",
subtypes: [
"DeleteActionMustBeFinal",
"TotalPrepaidGasExceeded",
"TotalNumberOfActionsExceeded",
"AddKeyMethodNamesNumberOfBytesExceeded",
"AddKeyMethodNameLengthExceeded",
"IntegerOverflow",
"InvalidAccountId",
"ContractSizeExceeded",
"FunctionCallMethodNameLengthExceeded",
"FunctionCallArgumentsLengthExceeded",
"UnsuitableStakingKey",
"FunctionCallZeroAttachedGas",
"DelegateActionMustBeOnlyOne",
"UnsupportedProtocolFeature"
],
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: ""
}
},
AltBn128InvalidInput: {
name: "AltBn128InvalidInput",
subtypes: [],
props: {
msg: ""
}
},
BadUTF16: {
name: "BadUTF16",
subtypes: [],
props: {}
},
BadUTF8: {
name: "BadUTF8",
subtypes: [],
props: {}
},
BalanceExceeded: {
name: "BalanceExceeded",
subtypes: [],
props: {}
},
BalanceMismatchError: {
name: "BalanceMismatchError",
subtypes: [],
props: {
final_accounts_balance: "",
final_postponed_receipts_balance: "",
forwarded_buffered_receipts_balance: "",
incoming_receipts_balance: "",
incoming_validator_rewards: "",
initial_accounts_balance: "",
initial_postponed_receipts_balance: "",
new_buffered_receipts_balance: "",
new_delayed_receipts_balance: "",
other_burnt_amount: "",
outgoing_receipts_balance: "",
processed_delayed_receipts_balance: "",
slashed_burnt_amount: "",
tx_burnt_amount: ""
}
},
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: ""
}
},
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: ""
}
},
DelegateActionExpired: {
name: "DelegateActionExpired",
subtypes: [],
props: {}
},
DelegateActionInvalidNonce: {
name: "DelegateActionInvalidNonce",
subtypes: [],
props: {
ak_nonce: "",
delegate_nonce: ""
}
},
DelegateActionInvalidSignature: {
name: "DelegateActionInvalidSignature",
subtypes: [],
props: {}
},
DelegateActionMustBeOnlyOne: {
name: "DelegateActionMustBeOnlyOne",
subtypes: [],
props: {}
},
DelegateActionNonceTooLarge: {
name: "DelegateActionNonceTooLarge",
subtypes: [],
props: {
delegate_nonce: "",
upper_bound: ""
}
},
DelegateActionSenderDoesNotMatchTxReceiver: {
name: "DelegateActionSenderDoesNotMatchTxReceiver",
subtypes: [],
props: {
receiver_id: "",
sender_id: ""
}
},
DeleteAccountStaking: {
name: "DeleteAccountStaking",
subtypes: [],
props: {
account_id: ""
}
},
DeleteAccountWithLargeState: {
name: "DeleteAccountWithLargeState",
subtypes: [],
props: {
account_id: ""
}
},
DeleteActionMustBeFinal: {
name: "DeleteActionMustBeFinal",
subtypes: [],
props: {}
},
DeleteKeyDoesNotExist: {
name: "DeleteKeyDoesNotExist",
subtypes: [],
props: {
account_id: "",
public_key: ""
}
},
DepositWithFunctionCall: {
name: "DepositWithFunctionCall",
subtypes: [],
props: {}
},
Deprecated: {
name: "Deprecated",
subtypes: [],
props: {
method_name: ""
}
},
Deserialization: {
name: "Deserialization",
subtypes: [],
props: {}
},
ECRecoverError: {
name: "ECRecoverError",
subtypes: [],
props: {
msg: ""
}
},
Ed25519VerifyInvalidInput: {
name: "Ed25519VerifyInvalidInput",
subtypes: [],
props: {
msg: ""
}
},
EmptyMethodName: {
name: "EmptyMethodName",
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: {}
},
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",
"ECRecoverError",
"AltBn128InvalidInput",
"Ed25519VerifyInvalidInput"
],
props: {}
},
IllegalArithmetic: {
name: "IllegalArithmetic",
subtypes: [],
props: {}
},
IncorrectCallIndirectSignature: {
name: "IncorrectCallIndirectSignature",
subtypes: [],
props: {}
},
IndirectCallToNull: {
name: "IndirectCallToNull",
subtypes: [],
props: {}
},
Instantiate: {
name: "Instantiate",
subtypes: [],
props: {}
},
InsufficientStake: {
name: "InsufficientStake",
subtypes: [],
props: {
account_id: "",
minimum_stake: "",
stake: ""
}
},
IntegerOverflow: {
name: "IntegerOverflow",
subtypes: [],
props: {}
},
InternalMemoryDeclared: {
name: "InternalMemoryDeclared",
subtypes: [],
props: {}
},
InvalidAccessKeyError: {
name: "InvalidAccessKeyError",
subtypes: [
"AccessKeyNotFound",
"ReceiverMismatch",
"MethodNameMismatch",
"RequiresFullAccess",
"NotEnoughAllowance",
"DepositWithFunctionCall"
],
props: {}
},
InvalidAccountId: {
name: "InvalidAccountId",
subtypes: [],
props: {}
},
InvalidChain: {
name: "InvalidChain",
subtypes: [],
props: {}
},
InvalidDataReceiverId: {
name: "InvalidDataReceiverId",
subtypes: [],
props: {
account_id: ""
}
},
InvalidIteratorIndex: {
name: "InvalidIteratorIndex",
subtypes: [],
props: {
iterator_index: ""
}
},
InvalidMethodName: {
name: "InvalidMethodName",
subtypes: [],
props: {}
},
InvalidNonce: {
name: "InvalidNonce",
subtypes: [],
props: {
ak_nonce: "",
tx_nonce: ""
}
},
InvalidPredecessorId: {
name: "InvalidPredecessorId",
subtypes: [],
props: {
account_id: ""
}
},
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: ""
}
},
InvalidReceiverId: {
name: "InvalidReceiverId",
subtypes: [],
props: {
account_id: ""
}
},
InvalidRegisterId: {
name: "InvalidRegisterId",
subtypes: [],
props: {
register_id: ""
}
},
InvalidSignature: {
name: "InvalidSignature",
subtypes: [],
props: {}
},
InvalidSignerId: {
name: "InvalidSignerId",
subtypes: [],
props: {
account_id: ""
}
},
InvalidTxError: {
name: "InvalidTxError",
subtypes: [
"InvalidAccessKeyError",
"InvalidSignerId",
"SignerDoesNotExist",
"InvalidNonce",
"NonceTooLarge",
"InvalidReceiverId",
"InvalidSignature",
"NotEnoughBalance",
"LackBalanceForState",
"CostOverflow",
"InvalidChain",
"Expired",
"ActionsValidation",
"TransactionSizeExceeded",
"StorageError",
"ShardCongested",
"ShardStuck"
],
props: {}
},
IteratorWasInvalidated: {
name: "IteratorWasInvalidated",
subtypes: [],
props: {
iterator_index: ""
}
},
KeyLengthExceeded: {
name: "KeyLengthExceeded",
subtypes: [],
props: {
length: "",
limit: ""
}
},
LackBalanceForState: {
name: "LackBalanceForState",
subtypes: [],
props: {
account_id: "",
amount: ""
}
},
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: {}
},
MethodNameMismatch: {
name: "MethodNameMismatch",
subtypes: [],
props: {
method_name: ""
}
},
MethodNotFound: {
name: "MethodNotFound",
subtypes: [],
props: {}
},
MethodResolveError: {
name: "MethodResolveError",
subtypes: [
"MethodEmptyName",
"MethodNotFound",
"MethodInvalidSignature"
],
props: {}
},
MisalignedAtomicAccess: {
name: "MisalignedAtomicAccess",
subtypes: [],
props: {}
},
NonceTooLarge: {
name: "NonceTooLarge",
subtypes: [],
props: {
tx_nonce: "",
upper_bound: ""
}
},
NotEnoughAllowance: {
name: "NotEnoughAllowance",
subtypes: [],
props: {
account_id: "",
allowance: "",
cost: "",
public_key: ""
}
},
NotEnoughBalance: {
name: "NotEnoughBalance",
subtypes: [],
props: {
balance: "",
cost: "",
signer_id: ""
}
},
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: ""
}
},
OnlyImplicitAccountCreationAllowed: {
name: "OnlyImplicitAccountCreationAllowed",
subtypes: [],
props: {
account_id: ""
}
},
PrepareError: {
name: "PrepareError",
subtypes: [
"Serialization",
"Deserialization",
"InternalMemoryDeclared",
"GasInstrumentation",
"StackHeightInstrumentation",
"Instantiate",
"Memory",
"TooManyFunctions",
"TooManyLocals"
],
props: {}
},
ProhibitedInView: {
name: "ProhibitedInView",
subtypes: [],
props: {
method_name: ""
}
},
ReceiptSizeExceeded: {
name: "ReceiptSizeExceeded",
subtypes: [],
props: {
limit: "",
size: ""
}
},
ReceiptValidationError: {
name: "ReceiptValidationError",
subtypes: [
"InvalidPredecessorId",
"InvalidReceiverId",
"InvalidSignerId",
"InvalidDataReceiverId",
"ReturnedValueLengthExceeded",
"NumberInputDataDependenciesExceeded",
"ActionsValidation",
"ReceiptSizeExceeded"
],
props: {}
},
ReceiverMismatch: {
name: "ReceiverMismatch",
subtypes: [],
props: {
ak_receiver: "",
tx_receiver: ""
}
},
RequiresFullAccess: {
name: "RequiresFullAccess",
subtypes: [],
props: {}
},
ReturnedValueLengthExceeded: {
name: "ReturnedValueLengthExceeded",
subtypes: [],
props: {
length: "",
limit: ""
}
},
Serialization: {
name: "Serialization",
subtypes: [],
props: {}
},
ShardCongested: {
name: "ShardCongested",
subtypes: [],
props: {
congestion_level: "",
shard_id: ""
}
},
ShardStuck: {
name: "ShardStuck",
subtypes: [],
props: {
missed_chunks: "",
shard_id: ""
}
},
SignerDoesNotExist: {
name: "SignerDoesNotExist",
subtypes: [],
props: {
signer_id: ""
}
},
StackHeightInstrumentation: {
name: "StackHeightInstrumentation",
subtypes: [],
props: {}
},
StackOverflow: {
name: "StackOverflow",
subtypes: [],
props: {}
},
TooManyFunctions: {
name: "TooManyFunctions",
subtypes: [],
props: {}
},
TooManyLocals: {
name: "TooManyLocals",
subtypes: [],
props: {}
},
TotalLogLengthExceeded: {
name: "TotalLogLengthExceeded",
subtypes: [],
props: {
length: "",
limit: ""
}
},
TotalNumberOfActionsExceeded: {
name: "TotalNumberOfActionsExceeded",
subtypes: [],
props: {
limit: "",
total_number_of_actions: ""
}
},
TotalPrepaidGasExceeded: {
name: "TotalPrepaidGasExceeded",
subtypes: [],
props: {
limit: "",
total_prepaid_gas: ""
}
},
TransactionSizeExceeded: {
name: "TransactionSizeExceeded",
subtypes: [],
props: {
limit: "",
size: ""
}
},
TriesToStake: {
name: "TriesToStake",
subtypes: [],
props: {
account_id: "",
balance: "",
locked: "",
stake: ""
}
},
TriesToUnstake: {
name: "TriesToUnstake",
subtypes: [],
props: {
account_id: ""
}
},
TxExecutionError: {
name: "TxExecutionError",
subtypes: [
"ActionError",
"InvalidTxError"
],
props: {}
},
Unreachable: {
name: "Unreachable",
subtypes: [],
props: {}
},
UnsuitableStakingKey: {
name: "UnsuitableStakingKey",
subtypes: [],
props: {
public_key: ""
}
},
UnsupportedProtocolFeature: {
name: "UnsupportedProtocolFeature",
subtypes: [],
props: {
protocol_feature: "",
version: ""
}
},
ValueLengthExceeded: {
name: "ValueLengthExceeded",
subtypes: [],
props: {
length: "",
limit: ""
}
},
WasmTrap: {
name: "WasmTrap",
subtypes: [
"Unreachable",
"IncorrectCallIndirectSignature",
"MemoryOutOfBounds",
"CallIndirectOOB",
"IllegalArithmetic",
"MisalignedAtomicAccess",
"IndirectCallToNull",
"StackOverflow",
"GenericTrap"
],
props: {}
},
WasmerCompileError: {
name: "WasmerCompileError",
subtypes: [],
props: {
msg: ""
}
},
Closed: {
name: "Closed",
subtypes: [],
props: {}
},
ServerError: {
name: "ServerError",
subtypes: [
"TxExecutionError",
"Timeout",
"Closed"
],
props: {}
},
Timeout: {
name: "Timeout",
subtypes: [],
props: {}
}
}
};
var mustacheHelpers = {
formatNear: () => (n, render) => formatNearAmount(render(n))
};
var ServerError = class extends TypedError {
};
function parseRpcError(errorObj) {
const result = {};
const errorClassName = walkSubtype(errorObj, rpc_error_schema_default.schema, result, "");
const error = new ServerError(formatError(errorClassName, result), errorClassName);
Object.assign(error, result);
return error;
}
function formatError(errorClassName, errorData) {
if (typeof ErrorMessages[errorClassName] === "string") {
return import_mustache.default.render(ErrorMessages[errorClassName], {
...errorData,
...mustacheHelpers
});
}
return JSON.stringify(errorData);
}
function walkSubtype(errorObj, schema, result, typeName) {
let error;
let type;
let errorTypeName;
for (const errorName in schema) {
if (isString(errorObj[errorName])) {
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 {
result.kind = errorObj;
return typeName;
}
}
function getErrorTypeFromErrorMessage(errorMessage, errorType) {
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 /wasm execution failed with error: CompilationError\(CodeDoesNotExist/.test(errorMessage):
return "CodeDoesNotExist";
case /wasm execution failed with error: FunctionCallError\(MethodResolveError\(MethodNotFound/.test(errorMessage):
return "MethodNotFound";
case /wasm execution failed with error: MethodResolveError\(MethodNotFound/.test(errorMessage):
return "MethodNotFound";
case /Transaction nonce \d+ must be larger than nonce of the used access key \d+/.test(errorMessage):
return "InvalidNonce";
default:
return errorType;
}
}
function isObject(n) {
return Object.prototype.toString.call(n) === "[object Object]";
}
function isString(n) {
return Object.prototype.toString.call(n) === "[object String]";
}
var ConsoleLogger = class {
constructor(logLevels) {
__publicField(this, "isLevelEnabled", (level) => {
return this.logLevels.includes(level);
});
this.logLevels = logLevels;
}
print(level, message, ...optionalParams) {
switch (level) {
case "error":
case "fatal":
return console.error(message, ...optionalParams);
case "warn":
return console.warn(message, ...optionalParams);
case "log":
return console.log(message, ...optionalParams);
case "debug":
case "verbose":
return console.debug(message, ...optionalParams);
}
}
verbose(message, ...optionalParams) {
if (!this.isLevelEnabled("verbose")) return;
this.print("verbose", message, ...optionalParams);
}
debug(message, ...optionalParams) {
if (!this.isLevelEnabled("debug")) return;
this.print("debug", message, ...optionalParams);
}
log(message, ...optionalParams) {
if (!this.isLevelEnabled("log")) return;
this.print("log", message, ...optionalParams);
}
warn(message, ...optionalParams) {
if (!this.isLevelEnabled("warn")) return;
this.print("warn", message, ...optionalParams);
}
error(message, ...optionalParams) {
if (!this.isLevelEnabled("error")) return;
this.print("error", message, ...optionalParams);
}
fatal(message, ...optionalParams) {
if (!this.isLevelEnabled("fatal")) return;
this.print("fatal", message, ...optionalParams);
}
};
var DEFAULT_LOG_LEVELS = [
"verbose",
"debug",
"log",
"warn",
"error",
"fatal"
];
var DEFAULT_LOGGER = new ConsoleLogger(DEFAULT_LOG_LEVELS);
var _a;
var Logger = (_a = class {
static error(message, ...optionalParams) {
this.instanceRef?.error(message, ...optionalParams);
}
/**
* Write a 'log' level log.
*/
static log(message, ...optionalParams) {
this.instanceRef?.log(message, ...optionalParams);
}
/**
* Write a 'warn' level log.
*/
static warn(message, ...optionalParams) {
this.instanceRef?.warn(message, ...optionalParams);
}
/**
* Write a 'debug' level log.
*/
static debug(message, ...optionalParams) {
this.instanceRef?.debug?.(message, ...optionalParams);
}
/**
* Write a 'verbose' level log.
*/
static verbose(message, ...optionalParams) {
this.instanceRef?.verbose?.(message, ...optionalParams);
}
static fatal(message, ...optionalParams) {
this.instanceRef?.fatal?.(message, ...optionalParams);
}
}, __publicField(_a, "instanceRef", DEFAULT_LOGGER), __publicField(_a, "overrideLogger", (logger) => {
_a.instanceRef = logger;
}), _a);
function sortBigIntAsc(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
function findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio, protocolVersion) {
if (protocolVersion && protocolVersion < 49) {
return findSeatPriceForProtocolBefore49(validators, maxNumberOfSeats);
}
if (!minimumStakeRatio) {
const deprecate = (0, import_depd.default)("findSeatPrice(validators, maxNumberOfSeats)");
deprecate("`use `findSeatPrice(validators, maxNumberOfSeats, minimumStakeRatio)` instead");
minimumStakeRatio = [1, 6250];
}
return findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio);
}
function findSeatPriceForProtocolBefore49(validators, numSeats) {
const stakes = validators.map((v) => BigInt(v.stake)).sort(sortBigIntAsc);
const num = BigInt(numSeats);
const stakesSum = stakes.reduce((a, b) => a + b);
if (stakesSum < num) {
throw new Error("Stakes are below seats");
}
let left = 1n, right = stakesSum + 1n;
while (left !== right - 1n) {
const mid = (left + right) / 2n;
let found = false;
let currentSum = 0n;
for (let i = 0; i < stakes.length; ++i) {
currentSum = currentSum + stakes[i] / mid;
if (currentSum >= num) {
left = mid;
found = true;
break;
}
}
if (!found) {
right = mid;
}
}
return left;
}
function findSeatPriceForProtocolAfter49(validators, maxNumberOfSeats, minimumStakeRatio) {
if (minimumStakeRatio.length != 2) {
throw Error("minimumStakeRatio should have 2 elements");
}
const stakes = validators.map((v) => BigInt(v.stake)).sort(sortBigIntAsc);
const stakesSum = stakes.reduce((a, b) => a + b);
if (validators.length < maxNumberOfSeats) {
return stakesSum * BigInt(minimumStakeRatio[0]) / BigInt(minimumStakeRatio[1]);
} else {
return stakes[0] + 1n;
}
}
// node_modules/borsh/lib/esm/types.js
var integers = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64"];
// node_modules/borsh/lib/esm/buffer.js
var EncodeBuffer = (
/** @class */
function() {
function EncodeBuffer2() {
this.offset = 0;
this.buffer_size = 256;
this.buffer = new ArrayBuffer(this.buffer_size);
this.view = new DataView(this.buffer);
}
EncodeBuffer2.prototype.resize_if_necessary = function(needed_space) {
if (this.buffer_size - this.offset < needed_space) {
this.buffer_size = Math.max(this.buffer_size * 2, this.buffer_size + needed_space);
var new_buffer = new ArrayBuffer(this.buffer_size);
new Uint8Array(new_buffer).set(new Uint8Array(this.buffer));
this.buffer = new_buffer;
this.view = new DataView(new_buffer);
}
};
EncodeBuffer2.prototype.get_used_buffer = function() {
return new Uint8Array(this.buffer).slice(0, this.offset);
};
EncodeBuffer2.prototype.store_value = function(value, type) {
var bSize = type.substring(1);
var size = parseInt(bSize) / 8;
this.resize_if_necessary(size);
var toCall = type[0] === "f" ? "setFloat".concat(bSize) : type[0] === "i" ? "setInt".concat(bSize) : "setUint".concat(bSize);
this.view[toCall](this.offset, value, true);
this.offset += size;
};
EncodeBuffer2.prototype.store_bytes = function(from) {
this.resize_if_necessary(from.length);
new Uint8Array(this.buffer).set(new Uint8Array(from), this.offset);
this.offset += from.length;
};
return EncodeBuffer2;
}()
);
var DecodeBuffer = (
/** @class */
function() {
function DecodeBuffer2(buf) {
this.offset = 0;
this.buffer_size = buf.length;
this.buffer = new ArrayBuffer(buf.length);
new Uint8Array(this.buffer).set(buf);
this.view = new DataView(this.buffer);
}
DecodeBuffer2.prototype.assert_enough_buffer = function(size) {
if (this.offset + size > this.buffer.byteLength) {
throw new Error("Error in schema, the buffer is smaller than expected");
}
};
DecodeBuffer2.prototype.consume_value = function(type) {
var bSize = type.substring(1);
var size = parseInt(bSize) / 8;
this.assert_enough_buffer(size);
var toCall = type[0] === "f" ? "getFloat".concat(bSize) : type[0] === "i" ? "getInt".concat(bSize) : "getUint".concat(bSize);
var ret = this.view[toCall](this.offset, true);
this.offset += size;
return ret;
};
DecodeBuffer2.prototype.consume_bytes = function(size) {
this.assert_enough_buffer(size);
var ret = this.buffer.slice(this.offset, this.offset + size);
this.offset += size;
return ret;
};
return DecodeBuffer2;
}()
);
// node_modules/borsh/lib/esm/utils.js
var __extends = /* @__PURE__ */ function() {
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
};
return extendStatics(d, b);
};
return function(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
function isArrayLike(value) {
return Array.isArray(value) || !!value && typeof value === "object" && "length" in value && typeof value.length === "number" && (value.length === 0 || value.length > 0 && value.length - 1 in value);
}
function expect_type(value, type, fieldPath) {
if (typeof value !== type) {
throw new Error("Expected ".concat(type, " not ").concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
}
}
function expect_bigint(value, fieldPath) {
var basicType = ["number", "string", "bigint", "boolean"].includes(typeof value);
var strObject = typeof value === "object" && value !== null && "toString" in value;
if (!basicType && !strObject) {
throw new Error("Expected bigint, number, boolean or string not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
}
}
function expect_same_size(length, expected, fieldPath) {
if (length !== expected) {
throw new Error("Array length ".concat(length, " does not match schema length ").concat(expected, " at ").concat(fieldPath.join(".")));
}
}
function expect_enum(value, fieldPath) {
if (typeof value !== "object" || value === null) {
throw new Error("Expected object not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
}
}
var VALID_STRING_TYPES = integers.concat(["bool", "string"]);
var VALID_OBJECT_KEYS = ["option", "enum", "array", "set", "map", "struct"];
var ErrorSchema = (
/** @class */
function(_super) {
__extends(ErrorSchema2, _super);
function ErrorSchema2(schema, expected) {
var message = "Invalid schema: ".concat(JSON.stringify(schema), " expected ").concat(expected);
return _super.call(this, message) || this;
}
return ErrorSchema2;
}(Error)
);
function validate_schema(schema) {
if (typeof schema === "string" && VALID_STRING_TYPES.includes(schema)) {
return;
}
if (schema && typeof schema === "object") {
var keys = Object.keys(schema);
if (keys.length === 1 && VALID_OBJECT_KEYS.includes(keys[0])) {
var key = keys[0];
if (key === "option")
return validate_schema(schema[key]);
if (key === "enum")
return validate_enum_schema(schema[key]);
if (key === "array")
return validate_array_schema(schema[key]);
if (key === "set")
return validate_schema(schema[key]);
if (key === "map")
return validate_map_schema(schema[key]);
if (key === "struct")
return validate_struct_schema(schema[key]);
}
}
throw new ErrorSchema(schema, VALID_OBJECT_KEYS.join(", ") + " or " + VALID_STRING_TYPES.join(", "));
}
function validate_enum_schema(schema) {
if (!Array.isArray(schema))
throw new ErrorSchema(schema, "Array");
for (var _i = 0, schema_1 = schema; _i < schema_1.length; _i++) {
var sch = schema_1[_i];
if (typeof sch !== "object" || !("struct" in sch)) {
throw new Error('Missing "struct" key in enum schema');
}
if (typeof sch.struct !== "object" || Object.keys(sch.struct).length !== 1) {
throw new Error('The "struct" in each enum must have a single key');
}
validate_schema({ struct: sch.struct });
}
}
function validate_array_schema(schema) {
if (typeof schema !== "object")
throw new ErrorSchema(schema, "{ type, len? }");
if (schema.len && typeof schema.len !== "number") {
throw new Error("Invalid schema: ".concat(schema));
}
if ("type" in schema)
return validate_schema(schema.type);
throw new ErrorSchema(schema, "{ type, len? }");
}
function validate_map_schema(schema) {
if (typeof schema === "object" && "key" in schema && "value" in schema) {
validate_schema(schema.key);
validate_schema(schema.value);
} else {
throw new ErrorSchema(schema, "{ key, value }");
}
}
function validate_struct_schema(schema) {
if (typeof schema !== "object")
throw new ErrorSchema(schema, "object");
for (var key in schema) {
validate_schema(schema[key]);
}
}
// node_modules/borsh/lib/esm/serialize.js
var BorshSerializer = (
/** @class */
function() {
function BorshSerializer2(checkTypes) {
this.encoded = new EncodeBuffer();
this.fieldPath = ["value"];
this.checkTypes = checkTypes;
}
BorshSerializer2.prototype.encode = function(value, schema) {
this.encode_value(value, schema);
return this.encoded.get_used_buffer();
};
BorshSerializer2.prototype.encode_value = function(value, schema) {
if (typeof schema === "string") {
if (integers.includes(schema))
return this.encode_integer(value, schema);
if (schema === "string")
return this.encode_string(value);
if (schema === "bool")
return this.encode_boolean(value);
}
if (typeof schema === "object") {
if ("option" in schema)
return this.encode_option(value, schema);
if ("enum" in schema)
return this.encode_enum(value, schema);
if ("array" in schema)
return this.encode_array(value, schema);
if ("set" in schema)
return this.encode_set(value, schema);
if ("map" in schema)
return this.encode_map(value, schema);
if ("struct" in schema)
return this.encode_struct(value, schema);
}
};
BorshSerializer2.prototype.encode_integer = function(value, schema) {
var size = parseInt(schema.substring(1));
if (size <= 32 || schema == "f64") {
this.checkTypes && expect_type(value, "number", this.fieldPath);
this.encoded.store_value(value, schema);
} else {
this.checkTypes && expect_bigint(value, this.fieldPath);
this.encode_bigint(BigInt(value), size);
}
};
BorshSerializer2.prototype.encode_bigint = function(value, size) {
var buffer_len = size / 8;
var buffer = new Uint8Array(buffer_len);
for (var i = 0; i < buffer_len; i++) {
buffer[i] = Number(value & BigInt(255));
value = value >> BigInt(8);
}
this.encoded.store_bytes(new Uint8Array(buffer));
};
BorshSerializer2.prototype.encode_string = function(value) {
this.checkTypes && expect_type(value, "string", this.fieldPath);
var _value = value;
this.encoded.store_value(_value.length, "u32");
for (var i = 0; i < _value.length; i++) {
this.encoded.store_value(_value.charCodeAt(i), "u8");
}
};
BorshSerializer2.prototype.encode_boolean = function(value) {
this.checkTypes && expect_type(value, "boolean", this.fieldPath);
this.encoded.store_value(value ? 1 : 0, "u8");
};
BorshSerializer2.prototype.encode_option = function(value, schema) {
if (value === null || value === void 0) {
this.encoded.store_value(0, "u8");
} else {
this.encoded.store_value(1, "u8");
this.encode_value(value, schema.option);
}
};
BorshSerializer2.prototype.encode_enum = function(value, schema) {
this.checkTypes && expect_enum(value, this.fieldPath);
var valueKey = Object.keys(value)[0];
for (var i = 0; i < schema["enum"].length; i++) {
var valueSchema = schema["enum"][i];
if (valueKey === Object.keys(valueSchema.struct)[0]) {
this.encoded.store_value(i, "u8");
return this.encode_struct(value, valueSchema);
}
}
throw new Error("Enum key (".concat(valueKey, ") not found in enum schema: ").concat(JSON.stringify(schema), " at ").concat(this.fieldPath.join(".")));
};
BorshSerializer2.prototype.encode_array = function(value, schema) {
if (isArrayLike(value))
return this.encode_arraylike(value, schema);
if (value instanceof ArrayBuffer)
return this.encode_buffer(value, schema);
throw new Error("Expected Array-like not ".concat(typeof value, "(").concat(value, ") at ").concat(this.fieldPath.join(".")));
};
BorshSerializer2.prototype.encode_arraylike = function(value, schema) {
if (schema.array.len) {
expect_same_size(value.length, schema.array.len, this.fieldPath);
} else {
this.encoded.store_value(value.length, "u32");
}
for (var i = 0; i < value.length; i++) {
this.encode_value(value[i], schema.array.type);
}
};
BorshSerializer2.prototype.encode_buffer = function(value, schema) {
if (schema.array.len) {
expect_same_size(value.byteLength, schema.array.len, this.fieldPath);
} else {
this.encoded.store_value(value.byteLength, "u32");
}
this.encoded.store_bytes(new Uint8Array(value));
};
BorshSerializer2.prototype.encode_set = function(value, schema) {
this.checkTypes && expect_type(value, "object", this.fieldPath);
var isSet = value instanceof Set;
var values = isSet ? Array.from(value.values()) : Object.values(value);
this.encoded.store_value(values.length, "u32");
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var value_1 = values_1[_i];
this.encode_value(value_1, schema.set);
}
};
BorshSerializer2.prototype.encode_map = function(value, schema) {
this.checkTypes && expect_type(value, "object", this.fieldPath);
var isMap = value instanceof Map;
var keys = isMap ? Array.from(value.keys()) : Object.keys(value);
this.encoded.store_value(keys.length, "u32");
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
this.encode_value(key, schema.map.key);
this.encode_value(isMap ? value.get(key) : value[key], schema.map.value);
}
};
BorshSerializer2.prototype.encode_struct = function(value, schema) {
this.checkTypes && expect_type(value, "object", this.fieldPath);
for (var _i = 0, _a2 = Object.keys(schema.struct); _i < _a2.length; _i++) {
var key = _a2[_i];
this.fieldPath.push(key);
this.encode_value(value[key], schema.struct[key]);
this.fieldPath.pop();
}
};
return BorshSerializer2;
}()
);
// node_modules/borsh/lib/esm/deserialize.js
var BorshDeserializer = (
/** @class */
function() {
function BorshDeserializer2(bufferArray) {
this.buffer = new DecodeBuffer(bufferArray);
}
BorshDeserializer2.prototype.decode = function(schema) {
return this.decode_value(schema);
};
BorshDeserializer2.prototype.decode_value = function(schema) {
if (typeof schema === "string") {
if (integers.includes(schema))
return this.decode_integer(schema);
if (schema === "string")
return this.decode_string();
if (schema === "bool")
return this.decode_boolean();
}
if (typeof schema === "object") {
if ("option" in schema)
return this.decode_option(schema);
if ("enum" in schema)
return this.decode_enum(schema);
if ("array" in schema)
return this.decode_array(schema);
if ("set" in schema)
return this.decode_set(schema);
if ("map" in schema)
return this.decode_map(schema);
if ("struct" in schema)
return this.decode_struct(schema);
}
throw new Error("Unsupported type: ".concat(schema));
};
BorshDeserializer2.prototype.decode_integer = function(schema) {
var size = parseInt(schema.substring(1));
if (size <= 32 || schema == "f64") {
return this.buffer.consume_value(schema);
}
return this.decode_bigint(size, schema.startsWith("i"));
};
BorshDeserializer2.prototype.decode_bigint = function(size, signed) {
if (signed === void 0) {
signed = false;
}
var buffer_len = size / 8;
var buffer = new Uint8Array(this.buffer.consume_bytes(buffer_len));
var bits = buffer.reduceRight(function(r, x) {
return r + x.toString(16).padStart(2, "0");
}, "");
if (signed && buffer[buffer_len - 1]) {
return BigInt.asIntN(size, BigInt("0x".concat(bits)));
}
return BigInt("0x".concat(bits));
};
BorshDeserializer2.prototype.decode_string = function() {
var len = this.decode_integer("u32");
var buffer = new Uint8Array(this.buffer.consume_bytes(len));
return String.fromCharCode.apply(null, buffer);
};
BorshDeserializer2.prototype.decode_boolean = function() {
return this.buffer.consume_value("u8") > 0;
};
BorshDeserializer2.prototype.decode_option = function(schema) {
var option = this.buffer.consume_value("u8");
if (option === 1) {
return this.decode_value(schema.option);
}
if (option !== 0) {
throw new Error("Invalid option ".concat(option));
}
return null;
};
BorshDeserializer2.prototype.decode_enum = function(schema) {
var _a2;
var valueIndex = this.buffer.consume_value("u8");
if (valueIndex > schema["enum"].length) {
throw new Error("Enum option ".concat(valueIndex, " is not available"));
}
var struct = schema["enum"][valueIndex].struct;
var key = Object.keys(struct)[0];
return _a2 = {}, _a2[key] = this.decode_value(struct[key]), _a2;
};
BorshDeserializer2.prototype.decode_array = function(schema) {
var result = [];
var len = schema.array.len ? schema.array.len : this.decode_integer("u32");
for (var i = 0; i < len; ++i) {
result.push(this.decode_value(schema.array.type));
}
return result;
};
BorshDeserializer2.prototype.decode_set = function(schema) {
var len = this.decode_integer("u32");
var result = /* @__PURE__ */ new Set();
for (var i = 0; i < len; ++i) {
result.add(this.decode_value(schema.set));
}
return result;
};
BorshDeserializer2.prototype.decode_map = function(schema) {
var len = this.decode_integer("u32");
var result = /* @__PURE__ */ new Map();
for (var i = 0; i < len; ++i) {
var key = this.decode_value(schema.map.key);
var value = this.decode_value(schema.map.value);
result.set(key, value);
}
return result;
};
BorshDeserializer2.prototype.decode_struct = function(schema) {
var result = {};
for (var key in schema.struct) {
result[key] = this.decode_value(schema.struct[key]);
}
return result;
};
return BorshDeserializer2;
}()
);
// node_modules/borsh/lib/esm/index.js
function serialize(schema, value, validate) {
if (validate === void 0) {
validate = true;
}
if (validate)
validate_schema(schema);
var serializer = new BorshSerializer(validate);
return serializer.encode(value, schema);
}
// node_modules/@near-js/transactions/lib/esm/schema.js
function encodeTransaction(transaction) {
const schema = "signature" in transaction ? SCHEMA.SignedTransaction : SCHEMA.Transaction;
return serialize(schema, transaction);
}
var SCHEMA = new class BorshSchema {
constructor() {
__publicField(this, "Ed25519Signature", {
struct: {
data: { array: { type: "u8", len: 64 } }
}
});
__publicField(this, "Secp256k1Signature", {
struct: {
data: { array: { type: "u8", len: 65 } }
}
});
__publicField(this, "Signature", {
enum: [
{ struct: { ed25519Signature: this.Ed25519Signature } },
{ struct: { secp256k1Signature: this.Secp256k1Signature } }
]
});
__publicField(this, "Ed25519Data", {
struct: {
data: { array: { type: "u8", len: 32 } }
}
});
__publicField(this, "Secp256k1Data", {
struct: {
data: { array: { type: "u8", len: 64 } }
}
});
__publicField(this, "PublicKey", {
enum: [
{ struct: { ed25519Key: this.Ed25519Data } },
{ struct: { secp256k1Key: this.Secp256k1Data } }
]
});
__publicField(this, "FunctionCallPermission", {
struct: {
allowance: { option: "u128" },
receiverId: "string",
methodNames: { array: { type: "string" } }
}
});
__publicField(this, "FullAccessPermission", {
struct: {}
});
__publicField(this, "AccessKeyPermission", {
enum: [
{ struct: { functionCall: this.FunctionCallPermission } },
{ struct: { fullAccess: this.FullAccessPermission } }
]
});
__publicField(this, "AccessKey", {
struct: {
nonce: "u64",
permission: this.AccessKeyPermission
}
});
__publicField(this, "CreateAccount", {
struct: {}
});
__publicField(this, "DeployContract", {
struct: {
code: { array: { type: "u8" } }
}
});
__publicField(this, "FunctionCall", {
struct: {
methodName: "string",
args: { array: { type: "u8" } },
gas: "u64",
deposit: "u128"
}
});
__publicField(this, "Transfer", {
struct: {
deposit: "u128"
}
});
__publicField(this, "Stake", {
struct: {
stake: "u128",
publicKey: this.PublicKey
}
});
__publicField(this, "AddKey", {
struct: {
publicKey: this.PublicKey,
accessKey: this.AccessKey
}
});
__publicField(this, "DeleteKey", {
struct: {
publicKey: this.PublicKey
}
});
__publicField(this, "DeleteAccount", {
struct: {
beneficiaryId: "string"
}
});
__publicField(this, "GlobalContractDeployMode", {
enum: [
{ struct: { CodeHash: { struct: {} } } },
{ struct: { AccountId: { struct: {} } } }
]
});
__publicField(this, "GlobalContractIdentifier", {
enum: [
{ struct: { CodeHash: { array: { type: "u8", len: 32 } } } },
{ struct: { AccountId: "string" } }
]
});
__publicField(this, "DeployGlobalContract", {
struct: {
code: { array: { type: "u8" } },
deployMode: this.GlobalContractDeployMode
}
});
__publicField(this, "UseGlobalContract", {
struct: {
contractIdentifier: this.GlobalContractIdentifier
}
});
__publicField(this, "DelegateActionPrefix", {
struct: {
prefix: "u32"
}
});
__publicField(this, "ClassicActions", {
enum: [
{ struct: { createAccount: this.CreateAccount } },
{ struct: { deployContract: this.DeployContract } },
{ struct: { functionCall: this.FunctionCall } },
{ struct: { transfer: this.Transfer } },
{ struct: { stake: this.Stake } },
{ struct: { addKey: this.AddKey } },
{ struct: { deleteKey: this.DeleteKey } },
{ struct: { deleteAccount: this.DeleteAccount } },
{ struct: { deployGlobalContract: this.DeployGlobalContract } },
{ struct: { useGlobalContract: this.UseGlobalContract } }
]
});
__publicField(this, "DelegateAction", {
struct: {
senderId: "string",
receiverId: "string",
actions: { array: { type: this.ClassicActions } },
nonce: "u64",
maxBlockHeight: "u64",
publicKey: this.PublicKey
}
});
__publicField(this, "SignedDelegate", {
struct: {
delegateAction: this.DelegateAction,
signature: this.Signature
}
});
__publicField(this, "Action", {
enum: [
{ struct: { createAccount: this.CreateAccount } },
{ struct: { deployContract: this.DeployContract } },
{ struct: { functionCall: this.FunctionCall } },
{ struct: { transfer: this.Transfer } },
{ struct: { stake: this.Stake } },
{ struct: { addKey: this.AddKey } },
{ struct: { deleteKey: this.DeleteKey } },
{ struct: { deleteAccount: this.DeleteAccount } },
{ struct: { signedDelegate: this.SignedDelegate } },
{ struct: { deployGlobalContract: this.DeployGlobalContract } },
{ struct: { useGlobalContract: this.UseGlobalContract } }
]
});
__publicField(this, "Transaction", {
struct: {
signerId: "string",
publicKey: this.PublicKey,
nonce: "u64",
receiverId: "string",
blockHash: { array: { type: "u8", len: 32 } },
actions: { array: { type: this.Action } }
}
});
__publicField(this, "SignedTransaction", {
struct: {
transaction: this.Transaction,
signature: this.Signature
}
});
}
}();
// node_modules/@near-js/providers/lib/esm/fetch_json.js
var import_exponential_backoff = __toESM(require_backoff(), 1);
var BACKOFF_MULTIPLIER = 1.5;
var RETRY_NUMBER = 10;
var RETRY_DELAY = 0;
function retryConfig(numOfAttempts = RETRY_NUMBER, timeMultiple = BACKOFF_MULTIPLIER, startingDelay = RETRY_DELAY) {
return {
numOfAttempts,
timeMultiple,
startingDelay,
retry: (e) => {
if ([503, 500, 408].includes(e.cause)) {
return true;
}
if (e.toString().includes("FetchError") || e.toString().includes("Failed to fetch")) {
return true;
}
return false;
}
};
}
var ProviderError = class extends Error {
constructor(message, options) {
super(message, options);
__publicField(this, "cause");
if (options.cause) {
this.cause = options.cause;
}
}
};
async function fetchJsonRpc(url, json, headers, retryConfig2) {
const response = await (0, import_exponential_backoff.backOff)(async () => {
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(json),
headers: { ...headers, "Content-Type": "application/json" }
});
const { ok, status } = res;
if (status === 500) {
throw new ProviderError("Internal server error", { cause: status });
} else if (status === 408) {
throw new ProviderError("Timeout error", { cause: status });
} else if (status === 400) {
throw new ProviderError("Request validation error", { cause: status });
} else if (status === 503) {
throw new ProviderError(`${url} unavailable`, { cause: status });
}
if (!ok) {
throw new ProviderError(await res.text(), { cause: status });
}
return res;
}, retryConfig2);
if (!response) {
throw new TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${url}.`, "RetriesExceeded");
}
return await response.json();
}
// node_modules/@near-js/providers/lib/esm/json-rpc-provider.js
var REQUEST_RETRY_NUMBER = 12;
var REQUEST_RETRY_WAIT = 500;
var REQUEST_RETRY_WAIT_BACKOFF = 1.5;
var _nextId = 123;
var JsonRpcProvider = class {
/**
* @param connectionInfo Connection info
*/
constructor(connectionInfo, options) {
/** @hidden */
__publicField(this, "connection");
/** @hidden */
__publicField(this, "options");
/** @hidden */
__publicField(this, "networkId");
this.connection = connectionInfo || { url: "" };
const defaultOptions = {
retries: REQUEST_RETRY_NUMBER,
wait: REQUEST_RETRY_WAIT,
backoff: REQUEST_RETRY_WAIT_BACKOFF
};
this.options = Object.assign({}, defaultOptions, options);
this.networkId = void 0;
}
async getNetworkId() {
if (this.networkId) return this.networkId;
const { chain_id } = await this.viewNodeStatus();
this.networkId = chain_id;
return this.networkId;
}
async getCurrentEpochSeatPrice() {
const { minimum_stake_ratio: minStakeRatio, protocol_version: protocolVersion } = await this.experimental_protocolConfig({ finality: "final" });
const { current_validators: currentValidators } = await this.viewValidators();
const maxNumberOfSeats = 300;
return findSeatPrice(currentValidators, maxNumberOfSeats, minStakeRatio, protocolVersion);
}
async getNextEpochSeatPrice() {
const { minimum_stake_ratio: minStakeRatio, protocol_version: protocolVersion } = await this.experimental_protocolConfig({ finality: "final" });
const { next_validators: nextValidators } = await this.viewValidators();
const maxNumberOfSeats = 300;
return findSeatPrice(nextValidators, maxNumberOfSeats, minStakeRatio, protocolVersion);
}
async viewAccessKey(accountId, publicKey, finalityQuery = { finality: "final" }) {
const data = await this.query({
...finalityQuery,
request_type: "view_access_key",
account_id: accountId,
public_key: publicKey.toString()
});
return {
...data,
nonce: BigInt(data.nonce)
};
}
async viewAccessKeyList(accountId, finalityQuery = { finality: "final" }) {
return this.query({
...finalityQuery,
request_type: "view_access_key_list",
account_id: accountId
});
}
async viewAccount(accountId, blockQuery = { finality: "final" }) {
const data = await this.query({
...blockQuery,
request_type: "view_account",
account_id: accountId
});
return {
...data,
amount: BigInt(data.amount),
locked: BigInt(data.locked)
};
}
async viewContractCode(contractId, blockQuery = { finality: "final" }) {
const data = await this.query({
...blockQuery,
request_type: "view_code",
account_id: contractId
});
return {
...data,
code: new Uint8Array(Buffer.from(data.code_base64, "base64"))
};
}
async viewContractState(contractId, prefix, blockQuery = { finality: "final" }) {
const prefixBase64 = Buffer.from(prefix || "").toString("base64");
return this.query({
...blockQuery,
request_type: "view_state",
account_id: contractId,
prefix_base64: prefixBase64
});
}
async callFunction(contractId, method, args, blockQuery = { finality: "final" }) {
const argsBase64 = Buffer.from(JSON.stringify(args)).toString("base64");
const data = await this.query({
...blockQuery,
request_type: "call_function",
account_id: contractId,
method_name: method,
args_base64: argsBase64
});
if (data.result.length === 0) {
return void 0;
}
return JSON.parse(Buffer.from(data.result).toString());
}
async callFunctionRaw(contractId, method, args, blockQuery = { finality: "final" }) {
const argsBase64 = Buffer.from(JSON.stringify(args)).toString("base64");
return await this.query({
...blockQuery,
request_type: "call_function",
account_id: contractId,
method_name: method,
args_base64: argsBase64
});
}
async viewBlock(blockQuery) {
const { finality } = blockQuery;
const { blockId } = blockQuery;
return this.sendJsonRpc("block", { block_id: blockId, finality });
}
async viewChunk(chunkId) {
return this.sendJsonRpc("chunk", [chunkId]);
}
async viewGasPrice(blockId) {
return this.sendJsonRpc("gas_price", [blockId || null]);
}
async viewNodeStatus() {
return this.sendJsonRpc("status", []);
}
async viewValidators(blockId) {
return this.sendJsonRpc("validators", [blockId || null]);
}
async viewTransactionStatus(txHash, accountId, waitUntil) {
const encodedTxHash = typeof txHash === "string" ? txHash : baseEncode(txHash);
return this.sendJsonRpc("tx", {
tx_hash: encodedTxHash,
sender_account_id: accountId,
wait_until: waitUntil
});
}
async viewTransactionStatusWithReceipts(txHash, accountId, waitUntil) {
const encodedTxHash = typeof txHash === "string" ? txHash : baseEncode(txHash);
return this.sendJsonRpc("EXPERIMENTAL_tx_status", {
tx_hash: encodedTxHash,
sender_account_id: accountId,
wait_until: waitUntil
});
}
async viewTransactionReceipt(receiptId) {
return this.sendJsonRpc("EXPERIMENTAL_receipt", {
receipt_id: receiptId
});
}
/**
* Gets the RPC's status
* @see [https://docs.near.org/docs/develop/front-end/rpc#general-validator-status](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
*
* @param signedTransaction The signed transaction being sent
* @param waitUntil
*/
async sendTransactionUntil(signedTransaction, waitUntil) {
const bytes = encodeTransaction(signedTransaction);
return this.sendJsonRpc("send_tx", { signed_tx_base64: Buffer.from(bytes).toString("base64"), wait_until: waitUntil });
}
/**
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see [https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*
* @param signedTransaction The signed transaction being sent
*/
async sendTransaction(signedTransaction) {
return this.sendTransactionUntil(signedTransaction, "EXECUTED_OPTIMISTIC");
}
/**
* 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) {
return this.sendTransactionUntil(signedTransaction, "NONE");
}
/**
* Gets a transaction's status from the RPC
* @see [https://docs.near.org/docs/develop/front-end/rpc#transaction-status](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*
* @param txHash A transaction hash as either a Uint8Array or a base58 encoded string
* @param accountId The NEAR account that signed the transaction
* @param waitUntil
*/
async txStatus(txHash, accountId, waitUntil = "EXECUTED_OPTIMISTIC") {
if (typeof txHash === "string") {
return this.txStatusString(txHash, accountId, waitUntil);
} else {
return this.txStatusUint8Array(txHash, accountId, waitUntil);
}
}
async txStatusUint8Array(txHash, accountId, waitUntil) {
return this.sendJsonRpc("tx", { tx_hash: baseEncode(txHash), sender_account_id: accountId, wait_until: waitUntil });
}
async txStatusString(txHash, accountId, waitUntil) {
return this.sendJsonRpc("tx", { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
}
/**
* 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
* @param waitUntil
* @returns {Promise<FinalExecutionOutcome>}
*/
async txStatusReceipts(txHash, accountId, waitUntil = "EXECUTED_OPTIMISTIC") {
if (typeof txHash === "string") {
return this.sendJsonRpc("EXPERIMENTAL_tx_status", { tx_hash: txHash, sender_account_id: accountId, wait_until: waitUntil });
} else {
return this.sendJsonRpc("EXPERIMENTAL_tx_status", { tx_hash: baseEncode(txHash), sender_account_id: accountId, wait_until: waitUntil });
}
}
/**
* Query the RPC by passing an {@link "@near-js/types".provider/request.RpcQueryRequest | RpcQueryRequest }
* @see [https://docs.near.org/api/rpc/contracts](https://docs.near.org/api/rpc/contracts)
*
* @typeParam T the shape of the returned query response
*/
async query(...args) {
let result;
if (args.length === 1) {
const { block_id, blockId, ...otherParams } = args[0];
result = await this.sendJsonRpc("query", { ...otherParams, block_id: block_id || blockId });
} else {
const [path, data] = args;
result = await this.sendJsonRpc("query", [path, data]);
}
if (result && result.error) {
throw new TypedError(
`Querying failed: ${result.error}.
${JSON.stringify(result, null, 2)}`,
getErrorTypeFromErrorMessage(result.error, result.error.name)
);
}
return result;
}
/**
* Query for block info from the RPC
* pass block_id OR finality as blockQuery, not both
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/
async block(blockQuery) {
const { finality } = blockQuery;
const { 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 [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*/
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 [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-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 [https://docs.near.org/api/rpc/network#validation-status](https://docs.near.org/api/rpc/network#validation-status)
*
* @param blockId Block hash or height, or null for latest.
*/
async validators(blockId) {
return this.sendJsonRpc("validators", [blockId]);
}
/**
* Gets the protocol config at a block from RPC
*
* @param blockReference specifies the block to get the protocol config for
*/
async experimental_protocolConfig(blockReference) {
const { blockId, ...otherParams } = blockReference;
return await this.sendJsonRpc("EXPERIMENTAL_protocol_config", { ...otherParams, block_id: blockId });
}
/**
* Gets a light client execution proof for verifying execution outcomes
* @see [https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof](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);
}
/**
* Returns the next light client block as far in the future as possible from the last known hash
* to still be able to validate from that hash. This will either return the last block of the
* next epoch, or the last final known block.
*
* @see [https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block](https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block)
*/
async nextLightClientBlock(request) {
return await this.sendJsonRpc("next_light_client_block", 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 [https://docs.near.org/api/rpc/gas](https://docs.near.org/api/rpc/gas)
*
* @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 request = {
method,
params,
id: _nextId++,
jsonrpc: "2.0"
};
const response = await fetchJsonRpc(this.connection.url, request, this.connection.headers, retryConfig(this.options.retries, this.options.backoff, this.options.wait));
if (response.error) {
if (typeof response.error.data === "object") {
if (typeof response.error.data.error_message === "string" && typeof response.error.data.error_type === "string") {
throw new TypedError(response.error.data.error_message, response.error.data.error_type);
}
throw parseRpcError(response.error.data);
} else {
const errorMessage = `[${response.error.code}] ${response.error.message}: ${response.error.data}`;
const errorType = getErrorTypeFromErrorMessage(response.error.data, "");
if (errorType) {
throw new TypedError(formatError(errorType, params), errorType);
}
throw new TypedError(errorMessage, response.error.name);
}
} else if (typeof response.result?.error === "string") {
const errorType = getErrorTypeFromErrorMessage(response.result.error, "");
if (errorType) {
throw new ServerError(formatError(errorType, params), errorType);
}
}
const { result } = response;
if (typeof result === "undefined") {
throw new TypedError(
`Exceeded ${this.options.retries} attempts for request to ${method}.`,
"RetriesExceeded"
);
}
return result;
}
};
// node_modules/@near-js/providers/lib/esm/failover-rpc-provider.js
var FailoverRpcProvider = class {
/**
* @param providers list of providers
*/
constructor(providers) {
/** @hidden */
__publicField(this, "providers");
__publicField(this, "currentProviderIndex");
if (providers.length === 0) {
throw new Error("At least one provider must be specified");
}
this.providers = providers;
this.currentProviderIndex = 0;
}
switchToNextProvider() {
if (this.providers.length === 1) return;
if (this.providers.length - 1 <= this.currentProviderIndex) {
this.currentProviderIndex = 0;
} else {
this.currentProviderIndex += 1;
}
Logger.debug(
`Switched to provider at the index ${this.currentProviderIndex}`
);
}
get currentProvider() {
const provider = this.providers[this.currentProviderIndex];
if (!provider)
throw new Error(
`Provider wasn't found at index ${this.currentProviderIndex}`
);
return provider;
}
async withBackoff(getResult) {
for (let i = 0; i < this.providers.length; i++) {
try {
const result = await getResult(this.currentProvider);
if (result) return result;
} catch (e) {
console.error(e);
this.switchToNextProvider();
}
}
throw new TypedError(
`Exceeded ${this.providers.length} providers to execute request`,
"RetriesExceeded"
);
}
/**
* Gets the RPC's status
* @see [https://docs.near.org/docs/develop/front-end/rpc#general-validator-status](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*/
async status() {
return this.withBackoff((currentProvider) => currentProvider.status());
}
async getNetworkId() {
return this.withBackoff((currentProvider) => currentProvider.getNetworkId());
}
async getCurrentEpochSeatPrice() {
return this.withBackoff((currentProvider) => currentProvider.getCurrentEpochSeatPrice());
}
async getNextEpochSeatPrice() {
return this.withBackoff((currentProvider) => currentProvider.getNextEpochSeatPrice());
}
async viewAccessKey(accountId, publicKey, finalityQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewAccessKey(accountId, publicKey, finalityQuery));
}
async viewAccessKeyList(accountId, finalityQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewAccessKeyList(accountId, finalityQuery));
}
async viewAccount(accountId, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewAccount(accountId, blockQuery));
}
async viewContractCode(accountId, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewContractCode(accountId, blockQuery));
}
async viewContractState(accountId, prefix, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewContractState(accountId, prefix, blockQuery));
}
async callFunction(accountId, method, args, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.callFunction(accountId, method, args, blockQuery));
}
async callFunctionRaw(accountId, method, args, blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.callFunctionRaw(accountId, method, args, blockQuery));
}
async viewBlock(blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.viewBlock(blockQuery));
}
async viewChunk(chunkId) {
return this.withBackoff((currentProvider) => currentProvider.viewChunk(chunkId));
}
async viewGasPrice(blockId) {
return this.withBackoff((currentProvider) => currentProvider.viewGasPrice(blockId));
}
async viewNodeStatus() {
return this.withBackoff((currentProvider) => currentProvider.viewNodeStatus());
}
async viewValidators(blockId) {
return this.withBackoff((currentProvider) => currentProvider.viewValidators(blockId));
}
async viewTransactionStatus(txHash, accountId, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.viewTransactionStatus(txHash, accountId, waitUntil));
}
async viewTransactionStatusWithReceipts(txHash, accountId, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.viewTransactionStatusWithReceipts(txHash, accountId, waitUntil));
}
async viewTransactionReceipt(receiptId) {
return this.withBackoff((currentProvider) => currentProvider.viewTransactionReceipt(receiptId));
}
async sendTransactionUntil(signedTransaction, waitUntil) {
return this.withBackoff((currentProvider) => currentProvider.sendTransactionUntil(signedTransaction, waitUntil));
}
/**
* Sends a signed transaction to the RPC and waits until transaction is fully complete
* @see [https://docs.near.org/docs/develop/front-end/rpc#send-transaction-await](https://docs.near.org/docs/develop/front-end/rpc#general-validator-status)
*
* @param signedTransaction The signed transaction being sent
*/
async sendTransaction(signedTransaction) {
return this.withBackoff(
(currentProvider) => currentProvider.sendTransaction(signedTransaction)
);
}
/**
* 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) {
return this.withBackoff(
(currentProvider) => currentProvider.sendTransactionAsync(signedTransaction)
);
}
/**
* Gets a transaction's status from the RPC
* @see [https://docs.near.org/docs/develop/front-end/rpc#transaction-status](https://docs.near.org/docs/develop/front-end/rpc#general-validator-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, waitUntil) {
return this.withBackoff(
(currentProvider) => currentProvider.txStatus(txHash, accountId, waitUntil)
);
}
/**
* 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, waitUntil) {
return this.withBackoff(
(currentProvider) => currentProvider.txStatusReceipts(txHash, accountId, waitUntil)
);
}
async query(paramsOrPath, data) {
if (data) {
return this.withBackoff(
(currentProvider) => currentProvider.query(paramsOrPath, data)
);
}
return this.withBackoff(
(currentProvider) => currentProvider.query(paramsOrPath)
);
}
/**
* Query for block info from the RPC
* pass block_id OR finality as blockQuery, not both
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*
* @param blockQuery {@link BlockReference} (passing a {@link BlockId} is deprecated)
*/
async block(blockQuery) {
return this.withBackoff((currentProvider) => currentProvider.block(blockQuery));
}
/**
* Query changes in block from the RPC
* pass block_id OR finality as blockQuery, not both
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*/
async blockChanges(blockQuery) {
return this.withBackoff(
(currentProvider) => currentProvider.blockChanges(blockQuery)
);
}
/**
* Queries for details about a specific chunk appending details of receipts and transactions to the same chunk data provided by a block
* @see [https://docs.near.org/api/rpc/block-chunk](https://docs.near.org/api/rpc/block-chunk)
*
* @param chunkId Hash of a chunk ID or shard ID
*/
async chunk(chunkId) {
return this.withBackoff((currentProvider) => currentProvider.chunk(chunkId));
}
/**
* Query validators of the epoch defined by the given block id.
* @see [https://docs.near.org/api/rpc/network#validation-status](https://docs.near.org/api/rpc/network#validation-status)
*
* @param blockId Block hash or height, or null for latest.
*/
async validators(blockId) {
return this.withBackoff((currentProvider) => currentProvider.validators(blockId));
}
/**
* Gets the protocol config at a block from RPC
*
* @param blockReference specifies the block to get the protocol config for
*/
async experimental_protocolConfig(blockReference) {
return this.withBackoff(
(currentProvider) => currentProvider.experimental_protocolConfig(blockReference)
);
}
/**
* Gets a light client execution proof for verifying execution outcomes
* @see [https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof](https://github.com/nearprotocol/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-proof)
*/
async lightClientProof(request) {
return this.withBackoff(
(currentProvider) => currentProvider.lightClientProof(request)
);
}
/**
* Returns the next light client block as far in the future as possible from the last known hash
* to still be able to validate from that hash. This will either return the last block of the
* next epoch, or the last final known block.
*
* @see [https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block](https://github.com/near/NEPs/blob/master/specs/ChainSpec/LightClient.md#light-client-block)
*/
async nextLightClientBlock(request) {
return this.withBackoff(
(currentProvider) => currentProvider.nextLightClientBlock(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) {
return this.withBackoff(
(currentProvider) => currentProvider.accessKeyChanges(accountIdArray, blockQuery)
);
}
/**
* 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) {
return this.withBackoff(
(currentProvider) => currentProvider.singleAccessKeyChanges(
accessKeyArray,
blockQuery
)
);
}
/**
* 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) {
return this.withBackoff(
(currentProvider) => currentProvider.accountChanges(accountIdArray, blockQuery)
);
}
/**
* 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 = "") {
return this.withBackoff(
(currentProvider) => currentProvider.contractStateChanges(
accountIdArray,
blockQuery,
keyPrefix
)
);
}
/**
* 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) {
return this.withBackoff(
(currentProvider) => currentProvider.contractCodeChanges(accountIdArray, blockQuery)
);
}
/**
* Returns gas price for a specific block_height or block_hash.
* @see [https://docs.near.org/api/rpc/gas](https://docs.near.org/api/rpc/gas)
*
* @param blockId Block hash or height, or null for latest.
*/
async gasPrice(blockId) {
return this.withBackoff((currentProvider) => currentProvider.gasPrice(blockId));
}
};
// src/nearProvider.ts
function getProvider(providers) {
const nearRpcProvidersJson = providers ? JSON.parse(providers) : { nearRpcProviders: null };
const networkId = "testnet";
function createDefaultProvider() {
return new JsonRpcProvider(
{
url: networkId === "testnet" ? "https://test.rpc.fastnear.com" : "https://free.rpc.fastnear.com"
},
{
retries: 3,
backoff: 2,
wait: 1e3
}
);
}
let provider;
if (nearRpcProvidersJson.nearRpcProviders) {
console.log("Using custom RPC providers");
const providers2 = nearRpcProvidersJson.nearRpcProviders.map(
(config) => new JsonRpcProvider(
config.connectionInfo,
config.options || {}
)
);
provider = new FailoverRpcProvider(providers2);
} else {
console.log("Using default RPC provider");
provider = createDefaultProvider();
}
console.log("near providers", provider.providers);
return provider;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getProvider
});
/*! Bundled license information:
mustache/mustache.js:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
depd/index.js:
(*!
* depd
* Copyright(c) 2014-2018 Douglas Christopher Wilson
* MIT Licensed
*)
@scure/base/lib/esm/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/