g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","//\n\nmodule.exports = function shallowEqual(objA, objB, compare, compareContext) {\n var ret = compare ? compare.call(compareContext, objA, objB) : void 0;\n\n if (ret !== void 0) {\n return !!ret;\n }\n\n if (objA === objB) {\n return true;\n }\n\n if (typeof objA !== \"object\" || !objA || typeof objB !== \"object\" || !objB) {\n return false;\n }\n\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);\n\n // Test for A's keys different from B.\n for (var idx = 0; idx < keysA.length; idx++) {\n var key = keysA[idx];\n\n if (!bHasOwnProperty(key)) {\n return false;\n }\n\n var valueA = objA[key];\n var valueB = objB[key];\n\n ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;\n\n if (ret === false || (ret === void 0 && valueA !== valueB)) {\n return false;\n }\n }\n\n return true;\n};\n","'use strict';\n\nmodule.exports = (string, separator) => {\n\tif (!(typeof string === 'string' && typeof separator === 'string')) {\n\t\tthrow new TypeError('Expected the arguments to be of type `string`');\n\t}\n\n\tif (separator === '') {\n\t\treturn [string];\n\t}\n\n\tconst separatorIndex = string.indexOf(separator);\n\n\tif (separatorIndex === -1) {\n\t\treturn [string];\n\t}\n\n\treturn [\n\t\tstring.slice(0, separatorIndex),\n\t\tstring.slice(separatorIndex + separator.length)\n\t];\n};\n","'use strict';\nmodule.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var h=require(\"react\"),n=require(\"use-sync-external-store/shim\");function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\nu(function(){f.hasValue=!0;f.value=d},[d]);w(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Similar to invariant but only logs a warning if the condition is not met.\n * This can be used to log issues in development environments in critical\n * paths. Removing the logging code for production environments will keep the\n * same logic and follow the same code paths.\n */\n\nvar __DEV__ = process.env.NODE_ENV !== 'production';\n\nvar warning = function() {};\n\nif (__DEV__) {\n var printWarning = function printWarning(format, args) {\n var len = arguments.length;\n args = new Array(len > 1 ? len - 1 : 0);\n for (var key = 1; key < len; key++) {\n args[key - 1] = arguments[key];\n }\n var argIndex = 0;\n var message = 'Warning: ' +\n format.replace(/%s/g, function() {\n return args[argIndex++];\n });\n if (typeof console !== 'undefined') {\n console.error(message);\n }\n try {\n // --- Welcome to debugging React ---\n // This error was thrown as a convenience so that you can use this stack\n // to find the callsite that caused this warning to fire.\n throw new Error(message);\n } catch (x) {}\n }\n\n warning = function(condition, format, args) {\n var len = arguments.length;\n args = new Array(len > 2 ? len - 2 : 0);\n for (var key = 2; key < len; key++) {\n args[key - 2] = arguments[key];\n }\n if (format === undefined) {\n throw new Error(\n '`warning(condition, format, ...args)` requires a warning ' +\n 'message argument'\n );\n }\n if (!condition) {\n printWarning.apply(null, [format].concat(args));\n }\n };\n}\n\nmodule.exports = warning;\n","export default function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n return Object.freeze(Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw)\n }\n }));\n}","import { markToTrack, getUntracked } from 'proxy-compare';\n\nconst isObject = (x) => typeof x === \"object\" && x !== null;\nconst proxyStateMap = /* @__PURE__ */ new WeakMap();\nconst refSet = /* @__PURE__ */ new WeakSet();\nconst buildProxyFunction = (objectIs = Object.is, newProxy = (target, handler) => new Proxy(target, handler), canProxy = (x) => isObject(x) && !refSet.has(x) && (Array.isArray(x) || !(Symbol.iterator in x)) && !(x instanceof WeakMap) && !(x instanceof WeakSet) && !(x instanceof Error) && !(x instanceof Number) && !(x instanceof Date) && !(x instanceof String) && !(x instanceof RegExp) && !(x instanceof ArrayBuffer), shouldTrapDefineProperty = (desc) => desc.configurable && desc.enumerable && desc.writable, defaultHandlePromise = (promise) => {\n switch (promise.status) {\n case \"fulfilled\":\n return promise.value;\n case \"rejected\":\n throw promise.reason;\n default:\n throw promise;\n }\n}, snapCache = /* @__PURE__ */ new WeakMap(), createSnapshot = (target, version, handlePromise = defaultHandlePromise) => {\n const cache = snapCache.get(target);\n if ((cache == null ? void 0 : cache[0]) === version) {\n return cache[1];\n }\n const snap = Array.isArray(target) ? [] : Object.create(Object.getPrototypeOf(target));\n markToTrack(snap, true);\n snapCache.set(target, [version, snap]);\n Reflect.ownKeys(target).forEach((key) => {\n if (Object.getOwnPropertyDescriptor(snap, key)) {\n return;\n }\n const value = Reflect.get(target, key);\n const desc = {\n value,\n enumerable: true,\n // This is intentional to avoid copying with proxy-compare.\n // It's still non-writable, so it avoids assigning a value.\n configurable: true\n };\n if (refSet.has(value)) {\n markToTrack(value, false);\n } else if (value instanceof Promise) {\n delete desc.value;\n desc.get = () => handlePromise(value);\n } else if (proxyStateMap.has(value)) {\n const [target2, ensureVersion] = proxyStateMap.get(\n value\n );\n desc.value = createSnapshot(\n target2,\n ensureVersion(),\n handlePromise\n );\n }\n Object.defineProperty(snap, key, desc);\n });\n return Object.preventExtensions(snap);\n}, proxyCache = /* @__PURE__ */ new WeakMap(), versionHolder = [1, 1], proxyFunction = (initialObject) => {\n if (!isObject(initialObject)) {\n throw new Error(\"object required\");\n }\n const found = proxyCache.get(initialObject);\n if (found) {\n return found;\n }\n let version = versionHolder[0];\n const listeners = /* @__PURE__ */ new Set();\n const notifyUpdate = (op, nextVersion = ++versionHolder[0]) => {\n if (version !== nextVersion) {\n version = nextVersion;\n listeners.forEach((listener) => listener(op, nextVersion));\n }\n };\n let checkVersion = versionHolder[1];\n const ensureVersion = (nextCheckVersion = ++versionHolder[1]) => {\n if (checkVersion !== nextCheckVersion && !listeners.size) {\n checkVersion = nextCheckVersion;\n propProxyStates.forEach(([propProxyState]) => {\n const propVersion = propProxyState[1](nextCheckVersion);\n if (propVersion > version) {\n version = propVersion;\n }\n });\n }\n return version;\n };\n const createPropListener = (prop) => (op, nextVersion) => {\n const newOp = [...op];\n newOp[1] = [prop, ...newOp[1]];\n notifyUpdate(newOp, nextVersion);\n };\n const propProxyStates = /* @__PURE__ */ new Map();\n const addPropListener = (prop, propProxyState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && propProxyStates.has(prop)) {\n throw new Error(\"prop listener already exists\");\n }\n if (listeners.size) {\n const remove = propProxyState[3](createPropListener(prop));\n propProxyStates.set(prop, [propProxyState, remove]);\n } else {\n propProxyStates.set(prop, [propProxyState]);\n }\n };\n const removePropListener = (prop) => {\n var _a;\n const entry = propProxyStates.get(prop);\n if (entry) {\n propProxyStates.delete(prop);\n (_a = entry[1]) == null ? void 0 : _a.call(entry);\n }\n };\n const addListener = (listener) => {\n listeners.add(listener);\n if (listeners.size === 1) {\n propProxyStates.forEach(([propProxyState, prevRemove], prop) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && prevRemove) {\n throw new Error(\"remove already exists\");\n }\n const remove = propProxyState[3](createPropListener(prop));\n propProxyStates.set(prop, [propProxyState, remove]);\n });\n }\n const removeListener = () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n propProxyStates.forEach(([propProxyState, remove], prop) => {\n if (remove) {\n remove();\n propProxyStates.set(prop, [propProxyState]);\n }\n });\n }\n };\n return removeListener;\n };\n const baseObject = Array.isArray(initialObject) ? [] : Object.create(Object.getPrototypeOf(initialObject));\n const trapSet = (hasPrevValue, prevValue, prop, value, setValue) => {\n if (hasPrevValue && (objectIs(prevValue, value) || proxyCache.has(value) && objectIs(prevValue, proxyCache.get(value)))) {\n return;\n }\n removePropListener(prop);\n if (isObject(value)) {\n value = getUntracked(value) || value;\n }\n let nextValue = value;\n if (value instanceof Promise) {\n value.then((v) => {\n value.status = \"fulfilled\";\n value.value = v;\n notifyUpdate([\"resolve\", [prop], v]);\n }).catch((e) => {\n value.status = \"rejected\";\n value.reason = e;\n notifyUpdate([\"reject\", [prop], e]);\n });\n } else {\n if (!proxyStateMap.has(value) && canProxy(value)) {\n nextValue = proxyFunction(value);\n }\n const childProxyState = !refSet.has(nextValue) && proxyStateMap.get(nextValue);\n if (childProxyState) {\n addPropListener(prop, childProxyState);\n }\n }\n setValue(nextValue);\n notifyUpdate([\"set\", [prop], value, prevValue]);\n };\n const handler = {\n deleteProperty(target, prop) {\n const prevValue = Reflect.get(target, prop);\n removePropListener(prop);\n const deleted = Reflect.deleteProperty(target, prop);\n if (deleted) {\n notifyUpdate([\"delete\", [prop], prevValue]);\n }\n return deleted;\n },\n set(target, prop, value, receiver) {\n const hasPrevValue = Reflect.has(target, prop);\n const prevValue = Reflect.get(target, prop, receiver);\n trapSet(hasPrevValue, prevValue, prop, value, (nextValue) => {\n Reflect.set(target, prop, nextValue, receiver);\n });\n return true;\n },\n defineProperty(target, prop, desc) {\n if (shouldTrapDefineProperty(desc)) {\n const prevDesc = Reflect.getOwnPropertyDescriptor(target, prop);\n if (!prevDesc || shouldTrapDefineProperty(prevDesc)) {\n trapSet(\n !!prevDesc && \"value\" in prevDesc,\n prevDesc == null ? void 0 : prevDesc.value,\n prop,\n desc.value,\n (nextValue) => {\n Reflect.defineProperty(target, prop, {\n ...desc,\n value: nextValue\n });\n }\n );\n return true;\n }\n }\n return Reflect.defineProperty(target, prop, desc);\n }\n };\n const proxyObject = newProxy(baseObject, handler);\n proxyCache.set(initialObject, proxyObject);\n const proxyState = [\n baseObject,\n ensureVersion,\n createSnapshot,\n addListener\n ];\n proxyStateMap.set(proxyObject, proxyState);\n Reflect.ownKeys(initialObject).forEach((key) => {\n const desc = Object.getOwnPropertyDescriptor(\n initialObject,\n key\n );\n if (\"value\" in desc) {\n proxyObject[key] = initialObject[key];\n delete desc.value;\n delete desc.writable;\n }\n Object.defineProperty(baseObject, key, desc);\n });\n return proxyObject;\n}) => [\n // public functions\n proxyFunction,\n // shared state\n proxyStateMap,\n refSet,\n // internal things\n objectIs,\n newProxy,\n canProxy,\n shouldTrapDefineProperty,\n defaultHandlePromise,\n snapCache,\n createSnapshot,\n proxyCache,\n versionHolder\n];\nconst [defaultProxyFunction] = buildProxyFunction();\nfunction proxy(initialObject = {}) {\n return defaultProxyFunction(initialObject);\n}\nfunction getVersion(proxyObject) {\n const proxyState = proxyStateMap.get(proxyObject);\n return proxyState == null ? void 0 : proxyState[1]();\n}\nfunction subscribe(proxyObject, callback, notifyInSync) {\n const proxyState = proxyStateMap.get(proxyObject);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && !proxyState) {\n console.warn(\"Please use proxy object\");\n }\n let promise;\n const ops = [];\n const addListener = proxyState[3];\n let isListenerActive = false;\n const listener = (op) => {\n ops.push(op);\n if (notifyInSync) {\n callback(ops.splice(0));\n return;\n }\n if (!promise) {\n promise = Promise.resolve().then(() => {\n promise = void 0;\n if (isListenerActive) {\n callback(ops.splice(0));\n }\n });\n }\n };\n const removeListener = addListener(listener);\n isListenerActive = true;\n return () => {\n isListenerActive = false;\n removeListener();\n };\n}\nfunction snapshot(proxyObject, handlePromise) {\n const proxyState = proxyStateMap.get(proxyObject);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && !proxyState) {\n console.warn(\"Please use proxy object\");\n }\n const [target, ensureVersion, createSnapshot] = proxyState;\n return createSnapshot(target, ensureVersion(), handlePromise);\n}\nfunction ref(obj) {\n refSet.add(obj);\n return obj;\n}\nconst unstable_buildProxyFunction = buildProxyFunction;\n\nexport { getVersion, proxy, ref, snapshot, subscribe, unstable_buildProxyFunction };\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { RouterCtrlState } from '../types/controllerTypes'\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n history: ['ConnectWallet'],\n view: 'ConnectWallet',\n data: undefined\n})\n\n// -- controller --------------------------------------------------- //\nexport const RouterCtrl = {\n state,\n\n subscribe(callback: (newState: RouterCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n push(view: RouterCtrlState['view'], data?: RouterCtrlState['data']) {\n if (view !== state.view) {\n state.view = view\n if (data) {\n state.data = data\n }\n state.history.push(view)\n }\n },\n\n reset(view: RouterCtrlState['view']) {\n state.view = view\n state.history = [view]\n },\n\n replace(view: RouterCtrlState['view']) {\n if (state.history.length > 1) {\n state.history[state.history.length - 1] = view\n state.view = view\n }\n },\n\n goBack() {\n if (state.history.length > 1) {\n state.history.pop()\n const [last] = state.history.slice(-1)\n state.view = last\n }\n },\n\n setData(data: RouterCtrlState['data']) {\n state.data = data\n }\n}\n","import { RouterCtrl } from '../controllers/RouterCtrl'\n\nexport const CoreUtil = {\n WALLETCONNECT_DEEPLINK_CHOICE: 'WALLETCONNECT_DEEPLINK_CHOICE',\n\n W3M_VERSION: 'W3M_VERSION',\n\n W3M_PREFER_INJECTED_URL_FLAG: 'w3mPreferInjected',\n\n RECOMMENDED_WALLET_AMOUNT: 9,\n\n isMobile() {\n if (typeof window !== 'undefined') {\n return Boolean(\n window.matchMedia('(pointer:coarse)').matches ||\n /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)\n )\n }\n\n return false\n },\n\n isAndroid() {\n return CoreUtil.isMobile() && navigator.userAgent.toLowerCase().includes('android')\n },\n\n isIos() {\n const ua = navigator.userAgent.toLowerCase()\n\n return CoreUtil.isMobile() && (ua.includes('iphone') || ua.includes('ipad'))\n },\n\n isHttpUrl(url: string) {\n return url.startsWith('http://') || url.startsWith('https://')\n },\n\n isArray(data?: T | T[]): data is T[] {\n return Array.isArray(data) && data.length > 0\n },\n\n formatNativeUrl(appUrl: string, wcUri: string, name: string): string {\n if (CoreUtil.isHttpUrl(appUrl)) {\n return this.formatUniversalUrl(appUrl, wcUri, name)\n }\n let safeAppUrl = appUrl\n if (!safeAppUrl.includes('://')) {\n safeAppUrl = appUrl.replaceAll('/', '').replaceAll(':', '')\n safeAppUrl = `${safeAppUrl}://`\n }\n if (!safeAppUrl.endsWith('/')) {\n safeAppUrl = `${safeAppUrl}/`\n }\n this.setWalletConnectDeepLink(safeAppUrl, name)\n const encodedWcUrl = encodeURIComponent(wcUri)\n\n return `${safeAppUrl}wc?uri=${encodedWcUrl}`\n },\n\n formatUniversalUrl(appUrl: string, wcUri: string, name: string): string {\n if (!CoreUtil.isHttpUrl(appUrl)) {\n return this.formatNativeUrl(appUrl, wcUri, name)\n }\n let safeAppUrl = appUrl\n if (!safeAppUrl.endsWith('/')) {\n safeAppUrl = `${safeAppUrl}/`\n }\n this.setWalletConnectDeepLink(safeAppUrl, name)\n const encodedWcUrl = encodeURIComponent(wcUri)\n\n return `${safeAppUrl}wc?uri=${encodedWcUrl}`\n },\n\n async wait(miliseconds: number) {\n return new Promise(resolve => {\n setTimeout(resolve, miliseconds)\n })\n },\n\n openHref(href: string, target: '_blank' | '_self') {\n window.open(href, target, 'noreferrer noopener')\n },\n\n setWalletConnectDeepLink(href: string, name: string) {\n try {\n localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE, JSON.stringify({ href, name }))\n } catch {\n console.info('Unable to set WalletConnect deep link')\n }\n },\n\n setWalletConnectAndroidDeepLink(wcUri: string) {\n try {\n const [href] = wcUri.split('?')\n localStorage.setItem(\n CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE,\n JSON.stringify({ href, name: 'Android' })\n )\n } catch {\n console.info('Unable to set WalletConnect android deep link')\n }\n },\n\n removeWalletConnectDeepLink() {\n try {\n localStorage.removeItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE)\n } catch {\n console.info('Unable to remove WalletConnect deep link')\n }\n },\n\n setWeb3ModalVersionInStorage() {\n try {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(CoreUtil.W3M_VERSION, process.env.ROLLUP_W3M_VERSION ?? 'UNKNOWN')\n }\n } catch {\n console.info('Unable to set Web3Modal version in storage')\n }\n },\n\n getWalletRouterData() {\n const routerData = RouterCtrl.state.data?.Wallet\n if (!routerData) {\n throw new Error('Missing \"Wallet\" view data')\n }\n\n return routerData\n },\n\n getSwitchNetworkRouterData() {\n const routerData = RouterCtrl.state.data?.SwitchNetwork\n if (!routerData) {\n throw new Error('Missing \"SwitchNetwork\" view data')\n }\n\n return routerData\n },\n\n isPreferInjectedFlag() {\n if (typeof location !== 'undefined') {\n const queryParams = new URLSearchParams(location.search)\n\n return queryParams.has(CoreUtil.W3M_PREFER_INJECTED_URL_FLAG)\n }\n\n return false\n }\n}\n","import type { ClientCtrlState } from '../types/controllerTypes'\n\n// -- initial state ------------------------------------------------ //\nlet client: ClientCtrlState['ethereumClient'] = undefined\n\n// -- controller -- As function to enable correct ssr handling\nexport const ClientCtrl = {\n ethereumClient: undefined,\n\n setEthereumClient(ethereumClient: ClientCtrlState['ethereumClient']) {\n client = ethereumClient\n },\n\n client() {\n if (client) {\n return client\n }\n\n throw new Error('ClientCtrl has no client set')\n }\n}\n","import { proxy, snapshot, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { EventsCtrlState, ModalEvent, ModalEventData } from '../types/controllerTypes'\n\n// -- helpers ------------------------------------------------------ //\nconst isEnabled =\n typeof location !== 'undefined' &&\n (location.hostname.includes('localhost') || location.protocol.includes('https'))\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n enabled: isEnabled,\n userSessionId: '',\n events: [],\n connectedWalletId: undefined\n})\n\n// -- controller --------------------------------------------------- //\nexport const EventsCtrl = {\n state,\n\n subscribe(callback: (newEvent: ModalEvent) => void) {\n return valtioSub(state.events, () => callback(snapshot(state.events[state.events.length - 1])))\n },\n\n initialize() {\n if (state.enabled && typeof crypto?.randomUUID !== 'undefined') {\n state.userSessionId = crypto.randomUUID()\n }\n },\n\n setConnectedWalletId(connectedWalletId: EventsCtrlState['connectedWalletId']) {\n state.connectedWalletId = connectedWalletId\n },\n\n click(data: ModalEventData) {\n if (state.enabled) {\n const event = {\n type: 'CLICK' as const,\n name: data.name,\n userSessionId: state.userSessionId,\n timestamp: Date.now(),\n data\n }\n state.events.push(event)\n }\n },\n\n track(data: ModalEventData) {\n if (state.enabled) {\n const event = {\n type: 'TRACK' as const,\n name: data.name,\n userSessionId: state.userSessionId,\n timestamp: Date.now(),\n data\n }\n state.events.push(event)\n }\n },\n\n view(data: ModalEventData) {\n if (state.enabled) {\n const event = {\n type: 'VIEW' as const,\n name: data.name,\n userSessionId: state.userSessionId,\n timestamp: Date.now(),\n data\n }\n state.events.push(event)\n }\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { OptionsCtrlState } from '../types/controllerTypes'\nimport { ClientCtrl } from './ClientCtrl'\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n selectedChain: undefined,\n chains: undefined,\n isCustomDesktop: false,\n isCustomMobile: false,\n isDataLoaded: false,\n isUiLoaded: false,\n isPreferInjected: false\n})\n\n// -- controller --------------------------------------------------- //\nexport const OptionsCtrl = {\n state,\n\n subscribe(callback: (newState: OptionsCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n setChains(chains?: OptionsCtrlState['chains']) {\n state.chains = chains\n },\n\n getSelectedChain() {\n const selectedChain = ClientCtrl.client().getNetwork().chain\n if (selectedChain) {\n state.selectedChain = selectedChain\n }\n\n return state.selectedChain\n },\n\n setSelectedChain(selectedChain: OptionsCtrlState['selectedChain']) {\n state.selectedChain = selectedChain\n },\n\n setIsCustomDesktop(isCustomDesktop: OptionsCtrlState['isCustomDesktop']) {\n state.isCustomDesktop = isCustomDesktop\n },\n\n setIsCustomMobile(isCustomMobile: OptionsCtrlState['isCustomMobile']) {\n state.isCustomMobile = isCustomMobile\n },\n\n setIsDataLoaded(isDataLoaded: OptionsCtrlState['isDataLoaded']) {\n state.isDataLoaded = isDataLoaded\n },\n\n setIsUiLoaded(isUiLoaded: OptionsCtrlState['isUiLoaded']) {\n state.isUiLoaded = isUiLoaded\n },\n\n setIsPreferInjected(isPreferInjected: OptionsCtrlState['isPreferInjected']) {\n state.isPreferInjected = isPreferInjected\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { ConfigCtrlState } from '../types/controllerTypes'\nimport { CoreUtil } from '../utils/CoreUtil'\nimport { ClientCtrl } from './ClientCtrl'\nimport { EventsCtrl } from './EventsCtrl'\nimport { OptionsCtrl } from './OptionsCtrl'\n\nconst state = proxy({\n projectId: '',\n mobileWallets: undefined,\n desktopWallets: undefined,\n walletImages: undefined,\n chainImages: undefined,\n tokenImages: undefined,\n tokenContracts: undefined,\n enableNetworkView: false,\n enableAccountView: true,\n enableExplorer: true,\n defaultChain: undefined,\n explorerExcludedWalletIds: undefined,\n explorerRecommendedWalletIds: undefined,\n termsOfServiceUrl: undefined,\n privacyPolicyUrl: undefined\n})\n\n// -- controller --------------------------------------------------- //\nexport const ConfigCtrl = {\n state,\n\n subscribe(callback: (newState: ConfigCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n setConfig(config: ConfigCtrlState) {\n EventsCtrl.initialize()\n OptionsCtrl.setIsCustomMobile(Boolean(config.mobileWallets?.length))\n OptionsCtrl.setIsCustomDesktop(Boolean(config.desktopWallets?.length))\n OptionsCtrl.setChains(ClientCtrl.client().chains)\n OptionsCtrl.setIsPreferInjected(\n ClientCtrl.client().isInjectedProviderInstalled() && CoreUtil.isPreferInjectedFlag()\n )\n\n if (config.defaultChain) {\n OptionsCtrl.setSelectedChain(config.defaultChain)\n }\n\n CoreUtil.setWeb3ModalVersionInStorage()\n\n Object.assign(state, config)\n }\n}\n","import { ConfigCtrl } from '../controllers/ConfigCtrl'\n\n// -- Constants -----------------------------------------------------\nexport const NAMESPACE = 'eip155'\nconst BLOCKCHAIN_API = 'https://rpc.walletconnect.com'\n\n// -- Utility -------------------------------------------------------\nexport const BlockchainApiUtil = {\n async getIdentity(address: string, chainId: number): Promise<{ name?: string; avatar?: string }> {\n const { projectId } = ConfigCtrl.state\n const chain_id = `${NAMESPACE}:${chainId}`\n const endpoint = `${BLOCKCHAIN_API}/v1/identity/${address}?chainId=${chain_id}&projectId=${projectId}`\n\n return (await fetch(endpoint)).json()\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { AccountCtrlState } from '../types/controllerTypes'\nimport { BlockchainApiUtil } from '../utils/BlockchainApiUtil'\nimport { ClientCtrl } from './ClientCtrl'\nimport { ConfigCtrl } from './ConfigCtrl'\nimport { OptionsCtrl } from './OptionsCtrl'\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n address: undefined,\n profileName: undefined,\n profileAvatar: undefined,\n profileLoading: false,\n balanceLoading: false,\n balance: undefined,\n isConnected: false\n})\n\n// -- controller --------------------------------------------------- //\nexport const AccountCtrl = {\n state,\n\n subscribe(callback: (newState: AccountCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n getAccount() {\n const account = ClientCtrl.client().getAccount()\n state.address = account.address\n state.isConnected = account.isConnected\n },\n\n async fetchProfile(\n preloadAvatarFn: (avatar: string) => Promise,\n profileAddress?: `0x${string}`\n ) {\n try {\n state.profileLoading = true\n state.profileName = null\n state.profileAvatar = null\n const address = profileAddress ?? state.address\n const mainnetId = 1\n const isMainnetConfigured = OptionsCtrl.state.chains?.find(chain => chain.id === mainnetId)\n if (address && isMainnetConfigured) {\n try {\n const profile = await BlockchainApiUtil.getIdentity(address, mainnetId)\n state.profileName = profile.name\n state.profileAvatar = profile.avatar\n } catch {\n // If problem resolving the identity using our own Identity API, fallback to RPC resolution\n const name = await ClientCtrl.client().fetchEnsName({ address, chainId: mainnetId })\n state.profileName = name\n if (name) {\n const avatar = await ClientCtrl.client().fetchEnsAvatar({ name, chainId: mainnetId })\n state.profileAvatar = avatar\n }\n }\n if (state.profileAvatar) {\n await preloadAvatarFn(state.profileAvatar)\n }\n }\n } finally {\n state.profileLoading = false\n }\n },\n\n async fetchBalance(balanceAddress?: `0x${string}`) {\n try {\n const { chain } = ClientCtrl.client().getNetwork()\n const { tokenContracts } = ConfigCtrl.state\n let token: `0x${string}` | undefined = undefined\n if (chain && tokenContracts) {\n token = tokenContracts[chain.id] as `0x${string}`\n }\n state.balanceLoading = true\n const address = balanceAddress ?? state.address\n if (address) {\n const balance = await ClientCtrl.client().fetchBalance({ address, token })\n state.balance = { amount: balance.formatted, symbol: balance.symbol }\n }\n } finally {\n state.balanceLoading = false\n }\n },\n\n setAddress(address: AccountCtrlState['address']) {\n state.address = address\n },\n\n setIsConnected(isConnected: AccountCtrlState['isConnected']) {\n state.isConnected = isConnected\n },\n\n resetBalance() {\n state.balance = undefined\n },\n\n resetAccount() {\n state.address = undefined\n state.isConnected = false\n state.profileName = undefined\n state.profileAvatar = undefined\n state.balance = undefined\n }\n}\n","import { ConfigCtrl } from '../controllers/ConfigCtrl'\nimport type { ListingParams, ListingResponse } from '../types/controllerTypes'\n\n// -- Helpers -------------------------------------------------------\nconst W3M_API = 'https://explorer-api.walletconnect.com'\nconst SDK_TYPE = 'w3m'\nconst SDK_VERSION = `js-${process.env.ROLLUP_W3M_VERSION}`\n\nasync function fetchListings(endpoint: string, params: ListingParams) {\n const allParams = { sdkType: SDK_TYPE, sdkVersion: SDK_VERSION, ...params }\n const url = new URL(endpoint, W3M_API)\n url.searchParams.append('projectId', ConfigCtrl.state.projectId)\n Object.entries(allParams).forEach(([key, value]) => {\n if (value) {\n url.searchParams.append(key, String(value))\n }\n })\n const request = await fetch(url)\n\n return request.json() as Promise\n}\n\n// -- Utility -------------------------------------------------------\nexport const ExplorerUtil = {\n async getDesktopListings(params: ListingParams) {\n return fetchListings('/w3m/v1/getDesktopListings', params)\n },\n\n async getMobileListings(params: ListingParams) {\n return fetchListings('/w3m/v1/getMobileListings', params)\n },\n\n async getInjectedListings(params: ListingParams) {\n return fetchListings('/w3m/v1/getInjectedListings', params)\n },\n\n async getAllListings(params: ListingParams) {\n return fetchListings('/w3m/v1/getAllListings', params)\n },\n\n getWalletImageUrl(imageId: string) {\n return `${W3M_API}/w3m/v1/getWalletImage/${imageId}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`\n },\n\n getAssetImageUrl(imageId: string) {\n return `${W3M_API}/w3m/v1/getAssetImage/${imageId}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`\n }\n}\n","import { proxy } from 'valtio/vanilla'\nimport type { ExplorerCtrlState, ListingParams } from '../types/controllerTypes'\nimport { CoreUtil } from '../utils/CoreUtil'\nimport { ExplorerUtil } from '../utils/ExplorerUtil'\nimport { ConfigCtrl } from './ConfigCtrl'\n\nconst isMobile = CoreUtil.isMobile()\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n wallets: { listings: [], total: 0, page: 1 },\n injectedWallets: [],\n search: { listings: [], total: 0, page: 1 },\n recomendedWallets: []\n})\n\n// -- controller --------------------------------------------------- //\nexport const ExplorerCtrl = {\n state,\n\n async getRecomendedWallets() {\n const { explorerRecommendedWalletIds, explorerExcludedWalletIds } = ConfigCtrl.state\n\n // Don't fetch recomended wallets\n if (\n explorerRecommendedWalletIds === 'NONE' ||\n (explorerExcludedWalletIds === 'ALL' && !explorerRecommendedWalletIds)\n ) {\n return state.recomendedWallets\n }\n\n // Fetch only recomended wallets defined in config\n if (CoreUtil.isArray(explorerRecommendedWalletIds)) {\n const recommendedIds = explorerRecommendedWalletIds.join(',')\n const params = { recommendedIds }\n const { listings } = await ExplorerUtil.getAllListings(params)\n const listingsArr = Object.values(listings)\n listingsArr.sort((a, b) => {\n const aIndex = explorerRecommendedWalletIds.indexOf(a.id)\n const bIndex = explorerRecommendedWalletIds.indexOf(b.id)\n\n return aIndex - bIndex\n })\n state.recomendedWallets = listingsArr\n }\n\n // Fetch default recomended wallets based on user's device, options and excluded config\n else {\n const isExcluded = CoreUtil.isArray(explorerExcludedWalletIds)\n const params = {\n page: 1,\n entries: CoreUtil.RECOMMENDED_WALLET_AMOUNT,\n version: 2,\n excludedIds: isExcluded ? explorerExcludedWalletIds.join(',') : undefined\n }\n const { listings } = isMobile\n ? await ExplorerUtil.getMobileListings(params)\n : await ExplorerUtil.getDesktopListings(params)\n state.recomendedWallets = Object.values(listings)\n }\n\n return state.recomendedWallets\n },\n\n async getWallets(params: ListingParams) {\n const extendedParams: ListingParams = { ...params }\n const { explorerRecommendedWalletIds, explorerExcludedWalletIds } = ConfigCtrl.state\n const { recomendedWallets } = state\n\n // Don't fetch any wallets if all are excluded\n if (explorerExcludedWalletIds === 'ALL') {\n return state.wallets\n }\n\n // Don't fetch recomended wallets, as we already have these\n if (recomendedWallets.length) {\n extendedParams.excludedIds = recomendedWallets.map(wallet => wallet.id).join(',')\n } else if (CoreUtil.isArray(explorerRecommendedWalletIds)) {\n extendedParams.excludedIds = explorerRecommendedWalletIds.join(',')\n }\n\n // Don't fetch user defined excluded wallets & recomended wallets\n if (CoreUtil.isArray(explorerExcludedWalletIds)) {\n extendedParams.excludedIds = [extendedParams.excludedIds, explorerExcludedWalletIds]\n .filter(Boolean)\n .join(',')\n }\n\n const { page, search } = params\n const { listings: listingsObj, total } = isMobile\n ? await ExplorerUtil.getMobileListings(extendedParams)\n : await ExplorerUtil.getDesktopListings(extendedParams)\n const listings = Object.values(listingsObj)\n const type = search ? 'search' : 'wallets'\n state[type] = {\n listings: [...state[type].listings, ...listings],\n total,\n page: page ?? 1\n }\n\n return { listings, total }\n },\n\n async getInjectedWallets() {\n const { listings: listingsObj } = await ExplorerUtil.getInjectedListings({})\n const listings = Object.values(listingsObj)\n state.injectedWallets = listings\n\n return state.injectedWallets\n },\n\n getWalletImageUrl(imageId: string) {\n return ExplorerUtil.getWalletImageUrl(imageId)\n },\n\n getAssetImageUrl(imageId: string) {\n return ExplorerUtil.getAssetImageUrl(imageId)\n },\n\n resetSearch() {\n state.search = { listings: [], total: 0, page: 1 }\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { WcConnectionCtrlState } from '../types/controllerTypes'\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n pairingEnabled: false,\n pairingUri: '',\n pairingError: false\n})\n\n// -- controller --------------------------------------------------- //\nexport const WcConnectionCtrl = {\n state,\n\n subscribe(callback: (newState: WcConnectionCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n setPairingUri(pairingUri: WcConnectionCtrlState['pairingUri']) {\n state.pairingUri = pairingUri\n },\n\n setPairingError(pairingError: WcConnectionCtrlState['pairingError']) {\n state.pairingError = pairingError\n },\n\n setPairingEnabled(pairingEnabled: WcConnectionCtrlState['pairingEnabled']) {\n state.pairingEnabled = pairingEnabled\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { ModalCtrlState } from '../types/controllerTypes'\nimport { CoreUtil } from '../utils/CoreUtil'\nimport { AccountCtrl } from './AccountCtrl'\nimport { ClientCtrl } from './ClientCtrl'\nimport { ConfigCtrl } from './ConfigCtrl'\nimport { OptionsCtrl } from './OptionsCtrl'\nimport { RouterCtrl } from './RouterCtrl'\nimport { WcConnectionCtrl } from './WcConnectionCtrl'\n\n// -- types -------------------------------------------------------- //\nexport interface OpenOptions {\n route?: 'Account' | 'ConnectWallet' | 'Help' | 'SelectNetwork'\n}\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n open: false\n})\n\n// -- controller --------------------------------------------------- //\nexport const ModalCtrl = {\n state,\n\n subscribe(callback: (newState: ModalCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n async open(options?: OpenOptions) {\n return new Promise(resolve => {\n const { isUiLoaded, isDataLoaded, isPreferInjected, selectedChain } = OptionsCtrl.state\n const { isConnected } = AccountCtrl.state\n const { enableNetworkView } = ConfigCtrl.state\n WcConnectionCtrl.setPairingEnabled(true)\n\n if (!isConnected) {\n CoreUtil.removeWalletConnectDeepLink()\n }\n\n if (options?.route) {\n RouterCtrl.reset(options.route)\n } else if (isConnected) {\n RouterCtrl.reset('Account')\n } else if (enableNetworkView) {\n RouterCtrl.reset('SelectNetwork')\n } else if (isPreferInjected) {\n ClientCtrl.client()\n .connectConnector('injected', selectedChain?.id)\n .catch(err => console.error(err))\n resolve()\n\n return\n } else {\n RouterCtrl.reset('ConnectWallet')\n }\n\n const { pairingUri } = WcConnectionCtrl.state\n // Open modal if essential async data is ready\n if (isUiLoaded && isDataLoaded && (pairingUri || isConnected)) {\n state.open = true\n resolve()\n }\n // Otherwise (slow network) re-attempt open checks\n else {\n const interval = setInterval(() => {\n const opts = OptionsCtrl.state\n const connection = WcConnectionCtrl.state\n if (opts.isUiLoaded && opts.isDataLoaded && (connection.pairingUri || isConnected)) {\n clearInterval(interval)\n state.open = true\n resolve()\n }\n }, 200)\n }\n })\n },\n\n close() {\n state.open = false\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { ThemeCtrlState } from '../types/controllerTypes'\n\n// -- initial state ------------------------------------------------ //\nfunction isDarkMode() {\n return typeof matchMedia !== 'undefined' && matchMedia('(prefers-color-scheme: dark)').matches\n}\n\nconst state = proxy({\n themeMode: isDarkMode() ? 'dark' : 'light'\n})\n\n// -- controller --------------------------------------------------- //\nexport const ThemeCtrl = {\n state,\n\n subscribe(callback: (newState: ThemeCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n setThemeConfig(theme: ThemeCtrlState) {\n const { themeMode, themeVariables } = theme\n\n if (themeMode) {\n state.themeMode = themeMode\n }\n\n if (themeVariables) {\n state.themeVariables = { ...themeVariables }\n }\n }\n}\n","import { proxy, subscribe as valtioSub } from 'valtio/vanilla'\nimport type { ToastCtrlState } from '../types/controllerTypes'\n\n// -- initial state ------------------------------------------------ //\nconst state = proxy({\n open: false,\n message: '',\n variant: 'success'\n})\n\n// -- controller --------------------------------------------------- //\nexport const ToastCtrl = {\n state,\n\n subscribe(callback: (newState: ToastCtrlState) => void) {\n return valtioSub(state, () => callback(state))\n },\n\n openToast(message: ToastCtrlState['message'], variant: ToastCtrlState['variant']) {\n state.open = true\n state.message = message\n state.variant = variant\n },\n\n closeToast() {\n state.open = false\n }\n}\n","import { asUint8Array } from './util/as-uint8array.js';\nexport function alloc(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.alloc != null) {\n return asUint8Array(globalThis.Buffer.alloc(size));\n }\n return new Uint8Array(size);\n}\nexport function allocUnsafe(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {\n return asUint8Array(globalThis.Buffer.allocUnsafe(size));\n }\n return new Uint8Array(size);\n}","import { allocUnsafe } from './alloc.js';\nimport { asUint8Array } from './util/as-uint8array.js';\nexport function concat(arrays, length) {\n if (!length) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}","import bases from './util/bases.js';\nimport { asUint8Array } from './util/as-uint8array.js';\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));\n }\n return base.decoder.decode(`${ base.prefix }${ string }`);\n}","import bases from './util/bases.js';\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');\n }\n return base.encoder.encode(array).substring(1);\n}","export function asUint8Array(buf) {\n if (globalThis.Buffer != null) {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n return buf;\n}","function base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256);\n var iFACTOR = Math.log(256) / Math.log(BASE);\n function encode(source) {\n if (source instanceof Uint8Array);\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n var size = (pend - pbegin) * iFACTOR + 1 >>> 0;\n var b58 = new Uint8Array(size);\n while (pbegin !== pend) {\n var carry = source[pbegin];\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {\n carry += 256 * b58[it1] >>> 0;\n b58[it1] = carry % BASE >>> 0;\n carry = carry / BASE >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n if (source[psz] === ' ') {\n return;\n }\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n var size = (source.length - psz) * FACTOR + 1 >>> 0;\n var b256 = new Uint8Array(size);\n while (source[psz]) {\n var carry = BASE_MAP[source.charCodeAt(psz)];\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {\n carry += BASE * b256[it3] >>> 0;\n b256[it3] = carry % 256 >>> 0;\n carry = carry / 256 >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n if (source[psz] === ' ') {\n return;\n }\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${ name } character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;","const empty = new Uint8Array(0);\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\nconst fromHex = hex => {\n const hexes = hex.match(/../g);\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n};\nconst equals = (aa, bb) => {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n};\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n};\nconst isBinary = o => o instanceof ArrayBuffer || ArrayBuffer.isView(o);\nconst fromString = str => new TextEncoder().encode(str);\nconst toString = b => new TextDecoder().decode(b);\nexport {\n equals,\n coerce,\n isBinary,\n fromHex,\n toHex,\n fromString,\n toString,\n empty\n};","import basex from '../../vendor/base-x.js';\nimport { coerce } from '../bytes.js';\nclass Encoder {\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${ this.prefix }${ this.baseEncode(bytes) }`;\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\nclass Decoder {\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${ JSON.stringify(text) }, ${ this.name } decoder only supports inputs prefixed with ${ this.prefix }`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n } else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder) {\n return decoder.decode(input);\n } else {\n throw RangeError(`Unable to decode multibase string ${ JSON.stringify(input) }, only inputs prefixed with ${ Object.keys(this.decoders) } are supported`);\n }\n }\n}\nexport const or = (left, right) => new ComposedDecoder({\n ...left.decoders || { [left.prefix]: left },\n ...right.decoders || { [right.prefix]: right }\n});\nexport class Codec {\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport const from = ({name, prefix, encode, decode}) => new Codec(name, prefix, encode, decode);\nexport const baseX = ({prefix, name, alphabet}) => {\n const {encode, decode} = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: text => coerce(decode(text))\n });\n};\nconst decode = (string, alphabet, bitsPerChar, name) => {\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n const out = new Uint8Array(end * bitsPerChar / 8 | 0);\n let bits = 0;\n let buffer = 0;\n let written = 0;\n for (let i = 0; i < end; ++i) {\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${ name } character`);\n }\n buffer = buffer << bitsPerChar | value;\n bits += bitsPerChar;\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 255 & buffer >> bits;\n }\n }\n if (bits >= bitsPerChar || 255 & buffer << 8 - bits) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n};\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0;\n let buffer = 0;\n for (let i = 0; i < data.length; ++i) {\n buffer = buffer << 8 | data[i];\n bits += 8;\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & buffer >> bits];\n }\n }\n if (bits) {\n out += alphabet[mask & buffer << bitsPerChar - bits];\n }\n if (pad) {\n while (out.length * bitsPerChar & 7) {\n out += '=';\n }\n }\n return out;\n};\nexport const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n};","import { from } from './base.js';\nimport {\n fromString,\n toString\n} from '../bytes.js';\nexport const identity = from({\n prefix: '\\0',\n name: 'identity',\n encode: buf => toString(buf),\n decode: str => fromString(str)\n});","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});","import { from } from './base.js';\nconst alphabet = Array.from('\\uD83D\\uDE80\\uD83E\\uDE90\\u2604\\uD83D\\uDEF0\\uD83C\\uDF0C\\uD83C\\uDF11\\uD83C\\uDF12\\uD83C\\uDF13\\uD83C\\uDF14\\uD83C\\uDF15\\uD83C\\uDF16\\uD83C\\uDF17\\uD83C\\uDF18\\uD83C\\uDF0D\\uD83C\\uDF0F\\uD83C\\uDF0E\\uD83D\\uDC09\\u2600\\uD83D\\uDCBB\\uD83D\\uDDA5\\uD83D\\uDCBE\\uD83D\\uDCBF\\uD83D\\uDE02\\u2764\\uD83D\\uDE0D\\uD83E\\uDD23\\uD83D\\uDE0A\\uD83D\\uDE4F\\uD83D\\uDC95\\uD83D\\uDE2D\\uD83D\\uDE18\\uD83D\\uDC4D\\uD83D\\uDE05\\uD83D\\uDC4F\\uD83D\\uDE01\\uD83D\\uDD25\\uD83E\\uDD70\\uD83D\\uDC94\\uD83D\\uDC96\\uD83D\\uDC99\\uD83D\\uDE22\\uD83E\\uDD14\\uD83D\\uDE06\\uD83D\\uDE44\\uD83D\\uDCAA\\uD83D\\uDE09\\u263A\\uD83D\\uDC4C\\uD83E\\uDD17\\uD83D\\uDC9C\\uD83D\\uDE14\\uD83D\\uDE0E\\uD83D\\uDE07\\uD83C\\uDF39\\uD83E\\uDD26\\uD83C\\uDF89\\uD83D\\uDC9E\\u270C\\u2728\\uD83E\\uDD37\\uD83D\\uDE31\\uD83D\\uDE0C\\uD83C\\uDF38\\uD83D\\uDE4C\\uD83D\\uDE0B\\uD83D\\uDC97\\uD83D\\uDC9A\\uD83D\\uDE0F\\uD83D\\uDC9B\\uD83D\\uDE42\\uD83D\\uDC93\\uD83E\\uDD29\\uD83D\\uDE04\\uD83D\\uDE00\\uD83D\\uDDA4\\uD83D\\uDE03\\uD83D\\uDCAF\\uD83D\\uDE48\\uD83D\\uDC47\\uD83C\\uDFB6\\uD83D\\uDE12\\uD83E\\uDD2D\\u2763\\uD83D\\uDE1C\\uD83D\\uDC8B\\uD83D\\uDC40\\uD83D\\uDE2A\\uD83D\\uDE11\\uD83D\\uDCA5\\uD83D\\uDE4B\\uD83D\\uDE1E\\uD83D\\uDE29\\uD83D\\uDE21\\uD83E\\uDD2A\\uD83D\\uDC4A\\uD83E\\uDD73\\uD83D\\uDE25\\uD83E\\uDD24\\uD83D\\uDC49\\uD83D\\uDC83\\uD83D\\uDE33\\u270B\\uD83D\\uDE1A\\uD83D\\uDE1D\\uD83D\\uDE34\\uD83C\\uDF1F\\uD83D\\uDE2C\\uD83D\\uDE43\\uD83C\\uDF40\\uD83C\\uDF37\\uD83D\\uDE3B\\uD83D\\uDE13\\u2B50\\u2705\\uD83E\\uDD7A\\uD83C\\uDF08\\uD83D\\uDE08\\uD83E\\uDD18\\uD83D\\uDCA6\\u2714\\uD83D\\uDE23\\uD83C\\uDFC3\\uD83D\\uDC90\\u2639\\uD83C\\uDF8A\\uD83D\\uDC98\\uD83D\\uDE20\\u261D\\uD83D\\uDE15\\uD83C\\uDF3A\\uD83C\\uDF82\\uD83C\\uDF3B\\uD83D\\uDE10\\uD83D\\uDD95\\uD83D\\uDC9D\\uD83D\\uDE4A\\uD83D\\uDE39\\uD83D\\uDDE3\\uD83D\\uDCAB\\uD83D\\uDC80\\uD83D\\uDC51\\uD83C\\uDFB5\\uD83E\\uDD1E\\uD83D\\uDE1B\\uD83D\\uDD34\\uD83D\\uDE24\\uD83C\\uDF3C\\uD83D\\uDE2B\\u26BD\\uD83E\\uDD19\\u2615\\uD83C\\uDFC6\\uD83E\\uDD2B\\uD83D\\uDC48\\uD83D\\uDE2E\\uD83D\\uDE46\\uD83C\\uDF7B\\uD83C\\uDF43\\uD83D\\uDC36\\uD83D\\uDC81\\uD83D\\uDE32\\uD83C\\uDF3F\\uD83E\\uDDE1\\uD83C\\uDF81\\u26A1\\uD83C\\uDF1E\\uD83C\\uDF88\\u274C\\u270A\\uD83D\\uDC4B\\uD83D\\uDE30\\uD83E\\uDD28\\uD83D\\uDE36\\uD83E\\uDD1D\\uD83D\\uDEB6\\uD83D\\uDCB0\\uD83C\\uDF53\\uD83D\\uDCA2\\uD83E\\uDD1F\\uD83D\\uDE41\\uD83D\\uDEA8\\uD83D\\uDCA8\\uD83E\\uDD2C\\u2708\\uD83C\\uDF80\\uD83C\\uDF7A\\uD83E\\uDD13\\uD83D\\uDE19\\uD83D\\uDC9F\\uD83C\\uDF31\\uD83D\\uDE16\\uD83D\\uDC76\\uD83E\\uDD74\\u25B6\\u27A1\\u2753\\uD83D\\uDC8E\\uD83D\\uDCB8\\u2B07\\uD83D\\uDE28\\uD83C\\uDF1A\\uD83E\\uDD8B\\uD83D\\uDE37\\uD83D\\uDD7A\\u26A0\\uD83D\\uDE45\\uD83D\\uDE1F\\uD83D\\uDE35\\uD83D\\uDC4E\\uD83E\\uDD32\\uD83E\\uDD20\\uD83E\\uDD27\\uD83D\\uDCCC\\uD83D\\uDD35\\uD83D\\uDC85\\uD83E\\uDDD0\\uD83D\\uDC3E\\uD83C\\uDF52\\uD83D\\uDE17\\uD83E\\uDD11\\uD83C\\uDF0A\\uD83E\\uDD2F\\uD83D\\uDC37\\u260E\\uD83D\\uDCA7\\uD83D\\uDE2F\\uD83D\\uDC86\\uD83D\\uDC46\\uD83C\\uDFA4\\uD83D\\uDE47\\uD83C\\uDF51\\u2744\\uD83C\\uDF34\\uD83D\\uDCA3\\uD83D\\uDC38\\uD83D\\uDC8C\\uD83D\\uDCCD\\uD83E\\uDD40\\uD83E\\uDD22\\uD83D\\uDC45\\uD83D\\uDCA1\\uD83D\\uDCA9\\uD83D\\uDC50\\uD83D\\uDCF8\\uD83D\\uDC7B\\uD83E\\uDD10\\uD83E\\uDD2E\\uD83C\\uDFBC\\uD83E\\uDD75\\uD83D\\uDEA9\\uD83C\\uDF4E\\uD83C\\uDF4A\\uD83D\\uDC7C\\uD83D\\uDC8D\\uD83D\\uDCE3\\uD83E\\uDD42');\nconst alphabetBytesToChars = alphabet.reduce((p, c, i) => {\n p[i] = c;\n return p;\n}, []);\nconst alphabetCharsToBytes = alphabet.reduce((p, c, i) => {\n p[c.codePointAt(0)] = i;\n return p;\n}, []);\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${ char }`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '\\uD83D\\uDE80',\n name: 'base256emoji',\n encode,\n decode\n});","var encode_1 = encode;\nvar MSB = 128, REST = 127, MSBALL = ~REST, INT = Math.pow(2, 31);\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = num & 255 | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = num & 255 | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 128, REST$1 = 127;\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (value) {\n return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;","import varint from '../vendor/varint.js';\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset);\n return [\n code,\n varint.decode.bytes\n ];\n};\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset);\n return target;\n};\nexport const encodingLength = int => {\n return varint.encodingLength(int);\n};","import {\n coerce,\n equals as equalBytes\n} from '../bytes.js';\nimport * as varint from '../varint.js';\nexport const create = (code, digest) => {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n};\nexport const decode = multihash => {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n};\nexport const equals = (a, b) => {\n if (a === b) {\n return true;\n } else {\n return a.code === b.code && a.size === b.size && equalBytes(a.bytes, b.bytes);\n }\n};\nexport class Digest {\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}","import * as Digest from './digest.js';\nexport const from = ({name, code, encode}) => new Hasher(name, code, encode);\nexport class Hasher {\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array ? Digest.create(this.code, result) : result.then(digest => Digest.create(this.code, digest));\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}","import { from } from './hasher.js';\nconst sha = name => async data => new Uint8Array(await crypto.subtle.digest(name, data));\nexport const sha256 = from({\n name: 'sha2-256',\n code: 18,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 19,\n encode: sha('SHA-512')\n});","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0;\nconst name = 'identity';\nconst encode = coerce;\nconst digest = input => Digest.create(code, encode(input));\nexport const identity = {\n code,\n name,\n encode,\n digest\n};","import { coerce } from '../bytes.js';\nexport const name = 'raw';\nexport const code = 85;\nexport const encode = node => coerce(node);\nexport const decode = data => coerce(data);","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 512;\nexport const encode = node => textEncoder.encode(JSON.stringify(node));\nexport const decode = data => JSON.parse(textDecoder.decode(data));","import * as varint from './varint.js';\nimport * as Digest from './hashes/digest.js';\nimport { base58btc } from './bases/base58.js';\nimport { base32 } from './bases/base32.js';\nimport { coerce } from './bytes.js';\nexport class CID {\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n this.byteOffset = bytes.byteOffset;\n this.byteLength = bytes.byteLength;\n this.asCID = this;\n this._baseCache = new Map();\n Object.defineProperties(this, {\n byteOffset: hidden,\n byteLength: hidden,\n code: readonly,\n version: readonly,\n multihash: readonly,\n bytes: readonly,\n _baseCache: hidden,\n asCID: hidden\n });\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n default: {\n const {code, multihash} = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return CID.createV0(multihash);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const {code, digest} = this.multihash;\n const multihash = Digest.create(code, digest);\n return CID.createV1(this.code, multihash);\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${ this.version } to version 0. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return other && this.code === other.code && this.version === other.version && Digest.equals(this.multihash, other.multihash);\n }\n toString(base) {\n const {bytes, version, _baseCache} = this;\n switch (version) {\n case 0:\n return toStringV0(bytes, _baseCache, base || base58btc.encoder);\n default:\n return toStringV1(bytes, _baseCache, base || base32.encoder);\n }\n }\n toJSON() {\n return {\n code: this.code,\n version: this.version,\n hash: this.multihash.bytes\n };\n }\n get [Symbol.toStringTag]() {\n return 'CID';\n }\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return 'CID(' + this.toString() + ')';\n }\n static isCID(value) {\n deprecate(/^0\\.0/, IS_CID_DEPRECATION);\n return !!(value && (value[cidSymbol] || value.asCID === value));\n }\n get toBaseEncodedString() {\n throw new Error('Deprecated, use .toString()');\n }\n get codec() {\n throw new Error('\"codec\" property is deprecated, use integer \"code\" property instead');\n }\n get buffer() {\n throw new Error('Deprecated .buffer property, use .bytes to get Uint8Array instead');\n }\n get multibaseName() {\n throw new Error('\"multibaseName\" property is deprecated');\n }\n get prefix() {\n throw new Error('\"prefix\" property is deprecated');\n }\n static asCID(value) {\n if (value instanceof CID) {\n return value;\n } else if (value != null && value.asCID === value) {\n const {version, code, multihash, bytes} = value;\n return new CID(version, code, multihash, bytes || encodeCID(version, code, multihash.bytes));\n } else if (value != null && value[cidSymbol] === true) {\n const {version, multihash, code} = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n } else {\n return null;\n }\n }\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${ DAG_PB_CODE }) block encoding`);\n } else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0 ? CID.createV0(digest) : CID.createV1(specs.codec, digest);\n return [\n cid,\n bytes.subarray(specs.size)\n ];\n }\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n version = 0;\n offset = 0;\n } else if (version === 1) {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${ version }`);\n }\n const prefixSize = offset;\n const multihashCode = next();\n const digestSize = next();\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return {\n version,\n codec,\n multihashCode,\n digestSize,\n multihashSize,\n size\n };\n }\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n cid._baseCache.set(prefix, source);\n return cid;\n }\n}\nconst parseCIDtoBytes = (source, base) => {\n switch (source[0]) {\n case 'Q': {\n const decoder = base || base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${ base58btc.prefix }${ source }`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base || base58btc;\n return [\n base58btc.prefix,\n decoder.decode(source)\n ];\n }\n case base32.prefix: {\n const decoder = base || base32;\n return [\n base32.prefix,\n decoder.decode(source)\n ];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [\n source[0],\n base.decode(source)\n ];\n }\n }\n};\nconst toStringV0 = (bytes, cache, base) => {\n const {prefix} = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${ base.name } encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n } else {\n return cid;\n }\n};\nconst toStringV1 = (bytes, cache, base) => {\n const {prefix} = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n } else {\n return cid;\n }\n};\nconst DAG_PB_CODE = 112;\nconst SHA_256_CODE = 18;\nconst encodeCID = (version, code, multihash) => {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n};\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\nconst readonly = {\n writable: false,\n configurable: false,\n enumerable: true\n};\nconst hidden = {\n writable: false,\n enumerable: false,\n configurable: false\n};\nconst version = '0.0.0-dev';\nconst deprecate = (range, message) => {\n if (range.test(version)) {\n console.warn(message);\n } else {\n throw new Error(message);\n }\n};\nconst IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release.\nFollowing code pattern:\n\nif (CID.isCID(value)) {\n doSomethingWithCID(value)\n}\n\nIs replaced with:\n\nconst cid = CID.asCID(value)\nif (cid) {\n // Make sure to use cid instead of value\n doSomethingWithCID(cid)\n}\n`;","import * as identityBase from './bases/identity.js';\nimport * as base2 from './bases/base2.js';\nimport * as base8 from './bases/base8.js';\nimport * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as sha2 from './hashes/sha2.js';\nimport * as identity from './hashes/identity.js';\nimport * as raw from './codecs/raw.js';\nimport * as json from './codecs/json.js';\nimport {\n CID,\n hasher,\n digest,\n varint,\n bytes\n} from './index.js';\nconst bases = {\n ...identityBase,\n ...base2,\n ...base8,\n ...base10,\n ...base16,\n ...base32,\n ...base36,\n ...base58,\n ...base64,\n ...base256emoji\n};\nconst hashes = {\n ...sha2,\n ...identity\n};\nconst codecs = {\n raw,\n json\n};\nexport {\n CID,\n hasher,\n digest,\n varint,\n bytes,\n hashes,\n bases,\n codecs\n};","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '../alloc.js';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: { decode }\n };\n}\nconst string = createCodec('utf8', 'u', buf => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, str => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', buf => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, str => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../types.js'\n\nexport type ParseAccountErrorType = ErrorType\n\nexport function parseAccount(account: Address | Account): Account {\n if (typeof account === 'string') return { address: account, type: 'json-rpc' }\n return account\n}\n","export const aggregate3Signature = '0x82ad56cb'\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { aggregate3Signature } from '../../constants/contract.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ChainDoesNotSupportContract,\n ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n RawContractError,\n type RawContractErrorType,\n} from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetCallErrorReturnType,\n getCallError,\n} from '../../utils/errors/getCallError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type CreateBatchSchedulerErrorType,\n createBatchScheduler,\n} from '../../utils/promise/createBatchScheduler.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type FormattedCall<\n TChain extends Chain | undefined = Chain | undefined,\n> = FormattedTransactionRequest\n\nexport type CallParameters<\n TChain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address\n batch?: boolean\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint\n blockTag?: never\n }\n | {\n blockNumber?: never\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag\n }\n )\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | ScheduleMulticallErrorType\n | RequestErrorType\n>\n\n/**\n * Executes a new message call immediately without submitting a transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/call.html\n * - JSON-RPC Methods: [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call)\n *\n * @param client - Client to use\n * @param parameters - {@link CallParameters}\n * @returns The call data. {@link CallReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { call } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await call(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function call(\n client: Client,\n args: CallParameters,\n): Promise {\n const {\n account: account_ = client.account,\n batch = Boolean(client.batch?.multicall),\n blockNumber,\n blockTag = 'latest',\n accessList,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n from: account?.address,\n accessList,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n if (batch && shouldPerformMulticall({ request })) {\n try {\n return await scheduleMulticall(client, {\n ...request,\n blockNumber,\n blockTag,\n } as unknown as ScheduleMulticallParameters)\n } catch (err) {\n if (\n !(err instanceof ClientChainNotConfiguredError) &&\n !(err instanceof ChainDoesNotSupportContract)\n )\n throw err\n }\n }\n\n const response = await client.request({\n method: 'eth_call',\n params: block\n ? [request as Partial, block]\n : [request as Partial],\n })\n if (response === '0x') return { data: undefined }\n return { data: response }\n } catch (err) {\n const data = getRevertErrorData(err)\n const { offchainLookup, offchainLookupSignature } = await import(\n '../../utils/ccip.js'\n )\n if (data?.slice(0, 10) === offchainLookupSignature && to) {\n return { data: await offchainLookup(client, { data, to }) }\n }\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n\n// We only want to perform a scheduled multicall if:\n// - The request has calldata,\n// - The request has a target address,\n// - The target address is not already the aggregate3 signature,\n// - The request has no other properties (`nonce`, `gas`, etc cannot be sent with a multicall).\nfunction shouldPerformMulticall({ request }: { request: TransactionRequest }) {\n const { data, to, ...request_ } = request\n if (!data) return false\n if (data.startsWith(aggregate3Signature)) return false\n if (!to) return false\n if (\n Object.values(request_).filter((x) => typeof x !== 'undefined').length > 0\n )\n return false\n return true\n}\n\ntype ScheduleMulticallParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n data: Hex\n multicallAddress?: Address\n to: Address\n}\n\nexport type ScheduleMulticallErrorType =\n | GetChainContractAddressErrorType\n | NumberToHexErrorType\n | CreateBatchSchedulerErrorType\n | EncodeFunctionDataErrorType\n | DecodeFunctionResultErrorType\n | RawContractErrorType\n | ErrorType\n\nasync function scheduleMulticall(\n client: Client,\n args: ScheduleMulticallParameters,\n) {\n const { batchSize = 1024, wait = 0 } =\n typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n const {\n blockNumber,\n blockTag = 'latest',\n data,\n multicallAddress: multicallAddress_,\n to,\n } = args\n\n let multicallAddress = multicallAddress_\n if (!multicallAddress) {\n if (!client.chain) throw new ClientChainNotConfiguredError()\n\n multicallAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const { schedule } = createBatchScheduler({\n id: `${client.uid}.${block}`,\n wait,\n shouldSplitBatch(args) {\n const size = args.reduce((size, { data }) => size + (data.length - 2), 0)\n return size > batchSize * 2\n },\n fn: async (\n requests: {\n data: Hex\n to: Address\n }[],\n ) => {\n const calls = requests.map((request) => ({\n allowFailure: true,\n callData: request.data,\n target: request.to,\n }))\n\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n args: [calls],\n functionName: 'aggregate3',\n })\n\n const data = await client.request({\n method: 'eth_call',\n params: [\n {\n data: calldata,\n to: multicallAddress,\n },\n block,\n ],\n })\n\n return decodeFunctionResult({\n abi: multicall3Abi,\n args: [calls],\n functionName: 'aggregate3',\n data: data || '0x',\n })\n },\n })\n\n const [{ returnData, success }] = await schedule({ data, to })\n\n if (!success) throw new RawContractError({ data: returnData })\n if (returnData === '0x') return { data: undefined }\n return { data: returnData }\n}\n\nexport type GetRevertErrorDataErrorType = ErrorType\n\nexport function getRevertErrorData(err: unknown) {\n if (!(err instanceof BaseError)) return undefined\n const error = err.walk() as RawContractError\n return typeof error.data === 'object' ? error.data.data : error.data\n}\n","import type { CallParameters } from '../../actions/public/call.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n CallExecutionError,\n type CallExecutionErrorType,\n} from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './getNodeError.js'\n\nexport type GetCallErrorReturnType = Omit<\n CallExecutionErrorType,\n 'cause'\n> & {\n cause: cause | GetNodeErrorReturnType\n}\n\nexport function getCallError>(\n err: err,\n {\n docsPath,\n ...args\n }: CallParameters & {\n chain?: Chain\n docsPath?: string\n },\n): GetCallErrorReturnType {\n const cause = (() => {\n const cause = getNodeError(\n err as {} as BaseError,\n args as GetNodeErrorParameters,\n )\n if (cause instanceof UnknownNodeError) return err as {} as BaseError\n return cause\n })()\n return new CallExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetCallErrorReturnType\n}\n","/* [Multicall3](https://github.com/mds1/multicall) */\nexport const multicall3Abi = [\n {\n inputs: [\n {\n components: [\n {\n name: 'target',\n type: 'address',\n },\n {\n name: 'allowFailure',\n type: 'bool',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n ],\n name: 'calls',\n type: 'tuple[]',\n },\n ],\n name: 'aggregate3',\n outputs: [\n {\n components: [\n {\n name: 'success',\n type: 'bool',\n },\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'returnData',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n\nconst universalResolverErrors = [\n {\n inputs: [],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [],\n name: 'ResolverWildcardNotSupported',\n type: 'error',\n },\n] as const\n\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolve',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n ],\n outputs: [\n { name: '', type: 'bytes' },\n { name: 'address', type: 'address' },\n ],\n },\n] as const\n\nexport const universalResolverReverseAbi = [\n ...universalResolverErrors,\n {\n name: 'reverse',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes', name: 'reverseName' }],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolvedAddress' },\n { type: 'address', name: 'reverseResolver' },\n { type: 'address', name: 'resolver' },\n ],\n },\n] as const\n\nexport const textResolverAbi = [\n {\n name: 'text',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes32' },\n { name: 'key', type: 'string' },\n ],\n outputs: [{ name: '', type: 'string' }],\n },\n] as const\n\nexport const addressResolverAbi = [\n {\n name: 'addr',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'name', type: 'bytes32' }],\n outputs: [{ name: '', type: 'address' }],\n },\n {\n name: 'addr',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes32' },\n { name: 'coinType', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bytes' }],\n },\n] as const\n\n// ERC-1271\n// isValidSignature(bytes32 hash, bytes signature) → bytes4 magicValue\nexport const smartAccountAbi = [\n {\n name: 'isValidSignature',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'hash', type: 'bytes32' },\n { name: 'signature', type: 'bytes' },\n ],\n outputs: [{ name: '', type: 'bytes4' }],\n },\n] as const\n\n// ERC-6492 - universal deployless signature validator contract\n// constructor(address _signer, bytes32 _hash, bytes _signature) → bytes4 returnValue\n// returnValue is either 0x1 (valid) or 0x0 (invalid)\nexport const universalSignatureValidatorAbi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: '_signer',\n type: 'address',\n },\n {\n internalType: 'bytes32',\n name: '_hash',\n type: 'bytes32',\n },\n {\n internalType: 'bytes',\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n] as const\n","import type { AbiError } from 'abitype'\n\n// https://docs.soliditylang.org/en/v0.8.16/control-structures.html#panic-via-assert-and-error-via-require\nexport const panicReasons = {\n 1: 'An `assert` condition failed.',\n 17: 'Arithmic operation resulted in underflow or overflow.',\n 18: 'Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).',\n 33: 'Attempted to convert to an invalid type.',\n 34: 'Attempted to access a storage byte array that is incorrectly encoded.',\n 49: 'Performed `.pop()` on an empty array',\n 50: 'Array index is out of bounds.',\n 65: 'Allocated too much memory or created an array which is too large.',\n 81: 'Attempted to call a zero-initialized variable of internal function type.',\n} as const\n\nexport const solidityError: AbiError = {\n inputs: [\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'Error',\n type: 'error',\n}\nexport const solidityPanic: AbiError = {\n inputs: [\n {\n name: 'reason',\n type: 'uint256',\n },\n ],\n name: 'Panic',\n type: 'error',\n}\n","export const etherUnits = {\n gwei: 9,\n wei: 18,\n}\nexport const gweiUnits = {\n ether: -9,\n wei: 9,\n}\nexport const weiUnits = {\n ether: -18,\n gwei: -9,\n}\n","import type { AbiEvent, AbiParameter } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { formatAbiItem, formatAbiParams } from '../utils/abi/formatAbiItem.js'\nimport { size } from '../utils/data/size.js'\n\nimport { BaseError } from './base.js'\n\nexport type AbiConstructorNotFoundErrorType = AbiConstructorNotFoundError & {\n name: 'AbiConstructorNotFoundError'\n}\nexport class AbiConstructorNotFoundError extends BaseError {\n override name = 'AbiConstructorNotFoundError'\n constructor({ docsPath }: { docsPath: string }) {\n super(\n [\n 'A constructor was not found on the ABI.',\n 'Make sure you are using the correct ABI and that the constructor exists on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\n override name = 'AbiConstructorParamsNotFoundError'\n constructor({ docsPath }: { docsPath: string }) {\n super(\n [\n 'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',\n 'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\n override name = 'AbiDecodingDataSizeInvalidError'\n constructor({ data, size }: { data: Hex; size: number }) {\n super(\n [\n `Data size of ${size} bytes is invalid.`,\n 'Size must be in increments of 32 bytes (size % 32 === 0).',\n ].join('\\n'),\n { metaMessages: [`Data: ${data} (${size} bytes)`] },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\n override name = 'AbiDecodingDataSizeTooSmallError'\n\n data: Hex\n params: readonly AbiParameter[]\n size: number\n\n constructor({\n data,\n params,\n size,\n }: { data: Hex; params: readonly AbiParameter[]; size: number }) {\n super(\n [`Data size of ${size} bytes is too small for given parameters.`].join(\n '\\n',\n ),\n {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n },\n )\n\n this.data = data\n this.params = params\n this.size = size\n }\n}\n\nexport type AbiDecodingZeroDataErrorType = AbiDecodingZeroDataError & {\n name: 'AbiDecodingZeroDataError'\n}\nexport class AbiDecodingZeroDataError extends BaseError {\n override name = 'AbiDecodingZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\n override name = 'AbiEncodingArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n [\n `ABI encoding array length mismatch for type ${type}.`,\n `Expected length: ${expectedLength}`,\n `Given length: ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\n override name = 'AbiEncodingBytesSizeMismatchError'\n constructor({ expectedSize, value }: { expectedSize: number; value: Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\n override name = 'AbiEncodingLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding params/values length mismatch.',\n `Expected length (params): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\n override name = 'AbiErrorInputsNotFoundError'\n constructor(errorName: string, { docsPath }: { docsPath: string }) {\n super(\n [\n `Arguments (\\`args\\`) were provided to \"${errorName}\", but \"${errorName}\" on the ABI does not contain any parameters (\\`inputs\\`).`,\n 'Cannot encode error result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the inputs exist on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n override name = 'AbiErrorNotFoundError'\n constructor(errorName?: string, { docsPath }: { docsPath?: string } = {}) {\n super(\n [\n `Error ${errorName ? `\"${errorName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\n override name = 'AbiErrorSignatureNotFoundError'\n\n signature: Hex\n\n constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n super(\n [\n `Encoded error signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n override name = 'AbiEventSignatureEmptyTopicsError'\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\n override name = 'AbiEventSignatureNotFoundError'\n constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n super(\n [\n `Encoded event signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n override name = 'AbiEventNotFoundError'\n constructor(eventName?: string, { docsPath }: { docsPath?: string } = {}) {\n super(\n [\n `Event ${eventName ? `\"${eventName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n override name = 'AbiFunctionNotFoundError'\n constructor(functionName?: string, { docsPath }: { docsPath?: string } = {}) {\n super(\n [\n `Function ${functionName ? `\"${functionName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\n override name = 'AbiFunctionOutputsNotFoundError'\n constructor(functionName: string, { docsPath }: { docsPath: string }) {\n super(\n [\n `Function \"${functionName}\" does not contain any \\`outputs\\` on ABI.`,\n 'Cannot decode function result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\n override name = 'AbiFunctionSignatureNotFoundError'\n constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n super(\n [\n `Encoded function signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n },\n )\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n override name = 'BytesSizeMismatchError'\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`)\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\n override name = 'DecodeLogDataMismatch'\n\n abiItem: AbiEvent\n data: Hex\n params: readonly AbiParameter[]\n size: number\n\n constructor({\n abiItem,\n data,\n params,\n size,\n }: {\n abiItem: AbiEvent\n data: Hex\n params: readonly AbiParameter[]\n size: number\n }) {\n super(\n [\n `Data size of ${size} bytes is too small for non-indexed event parameters.`,\n ].join('\\n'),\n {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n },\n )\n\n this.abiItem = abiItem\n this.data = data\n this.params = params\n this.size = size\n }\n}\n\nexport type DecodeLogTopicsMismatchErrorType = DecodeLogTopicsMismatch & {\n name: 'DecodeLogTopicsMismatch'\n}\nexport class DecodeLogTopicsMismatch extends BaseError {\n override name = 'DecodeLogTopicsMismatch'\n\n abiItem: AbiEvent\n\n constructor({\n abiItem,\n param,\n }: {\n abiItem: AbiEvent\n param: AbiParameter & { indexed: boolean }\n }) {\n super(\n [\n `Expected a topic for indexed event parameter${\n param.name ? ` \"${param.name}\"` : ''\n } on event \"${formatAbiItem(abiItem, { includeName: true })}\".`,\n ].join('\\n'),\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\n override name = 'InvalidAbiEncodingType'\n constructor(type: string, { docsPath }: { docsPath: string }) {\n super(\n [\n `Type \"${type}\" is not a valid encoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'),\n { docsPath },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\n override name = 'InvalidAbiDecodingType'\n constructor(type: string, { docsPath }: { docsPath: string }) {\n super(\n [\n `Type \"${type}\" is not a valid decoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'),\n { docsPath },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n override name = 'InvalidArrayError'\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'))\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\n override name = 'InvalidDefinitionTypeError'\n constructor(type: string) {\n super(\n [\n `\"${type}\" is not a valid definition type.`,\n 'Valid types: \"function\", \"event\", \"error\"',\n ].join('\\n'),\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n override name = 'UnsupportedPackedAbiType'\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`)\n }\n}\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n override name = 'InvalidAddressError'\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`)\n }\n}\n","import { getVersion } from './utils.js'\n\ntype BaseErrorParameters = {\n docsPath?: string\n docsSlug?: string\n metaMessages?: string[]\n} & (\n | {\n cause?: never\n details?: string\n }\n | {\n cause: BaseError | Error\n details?: never\n }\n)\n\nexport type BaseErrorType = BaseError & { name: 'ViemError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string\n metaMessages?: string[]\n shortMessage: string\n\n override name = 'ViemError'\n version = getVersion()\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n super()\n\n const details =\n args.cause instanceof BaseError\n ? args.cause.details\n : args.cause?.message\n ? args.cause.message\n : args.details!\n const docsPath =\n args.cause instanceof BaseError\n ? args.cause.docsPath || args.docsPath\n : args.docsPath\n\n this.message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath\n ? [\n `Docs: https://viem.sh${docsPath}.html${\n args.docsSlug ? `#${args.docsSlug}` : ''\n }`,\n ]\n : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: ${this.version}`,\n ].join('\\n')\n\n if (args.cause) this.cause = args.cause\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.shortMessage = shortMessage\n }\n\n walk(): Error\n walk(fn: (err: unknown) => boolean): Error | null\n walk(fn?: any): any {\n return walk(this, fn)\n }\n}\n\nfunction walk(err: unknown, fn?: (err: unknown) => boolean): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import type { Chain } from '../types/chain.js'\n\nimport { BaseError } from './base.js'\n\nexport type ChainDoesNotSupportContractErrorType =\n ChainDoesNotSupportContract & {\n name: 'ChainDoesNotSupportContract'\n }\nexport class ChainDoesNotSupportContract extends BaseError {\n override name = 'ChainDoesNotSupportContract'\n constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint\n chain: Chain\n contract: { name: string; blockCreated?: number }\n }) {\n super(\n `Chain \"${chain.name}\" does not support contract \"${contract.name}\".`,\n {\n metaMessages: [\n 'This could be due to any of the following:',\n ...(blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber\n ? [\n `- The contract \"${contract.name}\" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`,\n ]\n : [\n `- The chain does not have the contract \"${contract.name}\" configured.`,\n ]),\n ],\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\n override name = 'ChainMismatchError'\n\n constructor({\n chain,\n currentChainId,\n }: {\n chain: Chain\n currentChainId: number\n }) {\n super(\n `The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`,\n {\n metaMessages: [\n `Current Chain ID: ${currentChainId}`,\n `Expected Chain ID: ${chain.id} – ${chain.name}`,\n ],\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\n override name = 'ChainNotFoundError'\n\n constructor() {\n super(\n [\n 'No chain was provided to the request.',\n 'Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient.',\n ].join('\\n'),\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n override name = 'ClientChainNotConfiguredError'\n\n constructor() {\n super('No chain was provided to the Client.')\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n override name = 'InvalidChainIdError'\n\n constructor({ chainId }: { chainId: number }) {\n super(`Chain ID \"${chainId}\" is invalid.`)\n }\n}\n","import type { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName = true,\n includeName = false,\n}: {\n abiItem: AbiItem\n args: readonly unknown[]\n includeFunctionName?: boolean\n includeName?: boolean\n}) {\n if (!('name' in abiItem)) return\n if (!('inputs' in abiItem)) return\n if (!abiItem.inputs) return\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map(\n (input: AbiParameter, i: number) =>\n `${includeName && input.name ? `${input.name}: ` : ''}${\n typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n }`,\n )\n .join(', ')})`\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { parseAccount } from '../accounts/utils/parseAccount.js'\nimport type { CallParameters } from '../actions/public/call.js'\nimport { panicReasons } from '../constants/solidity.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\nimport {\n type DecodeErrorResultReturnType,\n decodeErrorResult,\n} from '../utils/abi/decodeErrorResult.js'\nimport { formatAbiItem } from '../utils/abi/formatAbiItem.js'\nimport { formatAbiItemWithArgs } from '../utils/abi/formatAbiItemWithArgs.js'\nimport { getAbiItem } from '../utils/abi/getAbiItem.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { AbiErrorSignatureNotFoundError } from './abi.js'\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\nimport { getContractAddress } from './utils.js'\n\nexport type CallExecutionErrorType = CallExecutionError & {\n name: 'CallExecutionError'\n}\nexport class CallExecutionError extends BaseError {\n override cause: BaseError\n\n override name = 'CallExecutionError'\n\n constructor(\n cause: BaseError,\n {\n account: account_,\n docsPath,\n chain,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n }: CallParameters & { chain?: Chain; docsPath?: string },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Raw Call Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n })\n this.cause = cause\n }\n}\n\nexport type ContractFunctionExecutionErrorType =\n ContractFunctionExecutionError & {\n name: 'ContractFunctionExecutionError'\n }\nexport class ContractFunctionExecutionError extends BaseError {\n abi: Abi\n args?: unknown[]\n override cause: BaseError\n contractAddress?: Address\n formattedArgs?: string\n functionName: string\n sender?: Address\n\n override name = 'ContractFunctionExecutionError'\n\n constructor(\n cause: BaseError,\n {\n abi,\n args,\n contractAddress,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args?: any\n contractAddress?: Address\n docsPath?: string\n functionName: string\n sender?: Address\n },\n ) {\n const abiItem = getAbiItem({ abi, args, name: functionName })\n const formattedArgs = abiItem\n ? formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName: false,\n includeName: false,\n })\n : undefined\n const functionWithParams = abiItem\n ? formatAbiItem(abiItem, { includeName: true })\n : undefined\n\n const prettyArgs = prettyPrint({\n address: contractAddress && getContractAddress(contractAddress),\n function: functionWithParams,\n args:\n formattedArgs &&\n formattedArgs !== '()' &&\n `${[...Array(functionName?.length ?? 0).keys()]\n .map(() => ' ')\n .join('')}${formattedArgs}`,\n sender,\n })\n\n super(\n cause.shortMessage ||\n `An unknown error occurred while executing the contract function \"${functionName}\".`,\n {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n },\n )\n this.abi = abi\n this.args = args\n this.cause = cause\n this.contractAddress = contractAddress\n this.functionName = functionName\n this.sender = sender\n }\n}\n\nexport type ContractFunctionRevertedErrorType =\n ContractFunctionRevertedError & {\n name: 'ContractFunctionRevertedError'\n }\nexport class ContractFunctionRevertedError extends BaseError {\n override name = 'ContractFunctionRevertedError'\n\n data?: DecodeErrorResultReturnType\n reason?: string\n signature?: Hex\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: { abi: Abi; data?: Hex; functionName: string; message?: string }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined = undefined\n let metaMessages\n let reason\n if (data && data !== '0x') {\n try {\n decodedData = decodeErrorResult({ abi, data })\n const { abiItem, errorName, args: errorArgs } = decodedData\n if (errorName === 'Error') {\n reason = (errorArgs as [string])[0]\n } else if (errorName === 'Panic') {\n const [firstArg] = errorArgs as [number]\n reason = panicReasons[firstArg as keyof typeof panicReasons]\n } else {\n const errorWithParams = abiItem\n ? formatAbiItem(abiItem, { includeName: true })\n : undefined\n const formattedArgs =\n abiItem && errorArgs\n ? formatAbiItemWithArgs({\n abiItem,\n args: errorArgs,\n includeFunctionName: false,\n includeName: false,\n })\n : undefined\n\n metaMessages = [\n errorWithParams ? `Error: ${errorWithParams}` : '',\n formattedArgs && formattedArgs !== '()'\n ? ` ${[...Array(errorName?.length ?? 0).keys()]\n .map(() => ' ')\n .join('')}${formattedArgs}`\n : '',\n ]\n }\n } catch (err) {\n cause = err as Error\n }\n } else if (message) reason = message\n\n let signature: Hex | undefined\n if (cause instanceof AbiErrorSignatureNotFoundError) {\n signature = cause.signature\n metaMessages = [\n `Unable to decode signature \"${signature}\" as it was not found on the provided ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ]\n }\n\n super(\n (reason && reason !== 'execution reverted') || signature\n ? [\n `The contract function \"${functionName}\" reverted with the following ${\n signature ? 'signature' : 'reason'\n }:`,\n reason || signature,\n ].join('\\n')\n : `The contract function \"${functionName}\" reverted.`,\n {\n cause,\n metaMessages,\n },\n )\n\n this.data = decodedData\n this.reason = reason\n this.signature = signature\n }\n}\n\nexport type ContractFunctionZeroDataErrorType =\n ContractFunctionZeroDataError & {\n name: 'ContractFunctionZeroDataError'\n }\nexport class ContractFunctionZeroDataError extends BaseError {\n override name = 'ContractFunctionZeroDataError'\n constructor({ functionName }: { functionName: string }) {\n super(`The contract function \"${functionName}\" returned no data (\"0x\").`, {\n metaMessages: [\n 'This could be due to any of the following:',\n ` - The contract does not have the function \"${functionName}\",`,\n ' - The parameters passed to the contract function may be invalid, or',\n ' - The address is not a contract.',\n ],\n })\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n override name = 'RawContractError'\n\n data?: Hex | { data?: Hex }\n\n constructor({\n data,\n message,\n }: { data?: Hex | { data?: Hex }; message?: string }) {\n super(message || '')\n this.data = data\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n override name = 'SliceOffsetOutOfBoundsError'\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \"${offset}\" is out-of-bounds (size: ${size}).`,\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n override name = 'SizeExceedsPaddingSizeError'\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'hex' | 'bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`,\n )\n }\n}\n","import type { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type DataLengthTooLongErrorType = DataLengthTooLongError & {\n name: 'DataLengthTooLongError'\n}\n/** @deprecated */\nexport class DataLengthTooLongError extends BaseError {\n override name = 'DataLengthTooLongError'\n constructor({ consumed, length }: { consumed: number; length: number }) {\n super(\n `Consumed bytes (${consumed}) is shorter than data length (${\n length - 1\n }).`,\n )\n }\n}\n\nexport type DataLengthTooShortErrorType = DataLengthTooShortError & {\n name: 'DataLengthTooShortError'\n}\n/** @deprecated */\nexport class DataLengthTooShortError extends BaseError {\n override name = 'DataLengthTooShortError'\n constructor({ length, dataLength }: { length: number; dataLength: number }) {\n super(\n `Data length (${dataLength - 1}) is shorter than consumed bytes length (${\n length - 1\n }).`,\n )\n }\n}\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n override name = 'IntegerOutOfRangeError'\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string\n min: string\n signed?: boolean\n size?: number\n value: string\n }) {\n super(\n `Number \"${value}\" is not in safe ${\n size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''\n }integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`,\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\n override name = 'InvalidBytesBooleanError'\n constructor(bytes: ByteArray) {\n super(\n `Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\n override name = 'InvalidHexBooleanError'\n constructor(hex: Hex) {\n super(\n `Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`,\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n override name = 'InvalidHexValueError'\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n )\n }\n}\n\nexport type OffsetOutOfBoundsErrorType = OffsetOutOfBoundsError & {\n name: 'OffsetOutOfBoundsError'\n}\n/** @deprecated */\nexport class OffsetOutOfBoundsError extends BaseError {\n override name = 'OffsetOutOfBoundsError' as const\n constructor({ nextOffset, offset }: { nextOffset: number; offset: number }) {\n super(\n `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`,\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n override name = 'SizeOverflowError' as const\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n )\n }\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\n\n/**\n * geth: https://github.com/ethereum/go-ethereum/blob/master/core/error.go\n * https://github.com/ethereum/go-ethereum/blob/master/core/types/transaction.go#L34-L41\n *\n * erigon: https://github.com/ledgerwatch/erigon/blob/master/core/error.go\n * https://github.com/ledgerwatch/erigon/blob/master/core/types/transaction.go#L41-L46\n *\n * anvil: https://github.com/foundry-rs/foundry/blob/master/anvil/src/eth/error.rs#L108\n */\nexport type ExecutionRevertedErrorType = ExecutionRevertedError & {\n code: 3\n name: 'ExecutionRevertedError'\n}\nexport class ExecutionRevertedError extends BaseError {\n static code = 3\n static nodeMessage = /execution reverted/\n\n override name = 'ExecutionRevertedError'\n\n constructor({\n cause,\n message,\n }: { cause?: BaseError; message?: string } = {}) {\n const reason = message\n ?.replace('execution reverted: ', '')\n ?.replace('execution reverted', '')\n super(\n `Execution reverted ${\n reason ? `with reason: ${reason}` : 'for an unknown reason'\n }.`,\n {\n cause,\n },\n )\n }\n}\n\nexport type FeeCapTooHighErrorType = FeeCapTooHighError & {\n name: 'FeeCapTooHighError'\n}\nexport class FeeCapTooHighError extends BaseError {\n static nodeMessage =\n /max fee per gas higher than 2\\^256-1|fee cap higher than 2\\^256-1/\n override name = 'FeeCapTooHigh'\n constructor({\n cause,\n maxFeePerGas,\n }: { cause?: BaseError; maxFeePerGas?: bigint } = {}) {\n super(\n `The fee cap (\\`maxFeePerGas\\`${\n maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''\n }) cannot be higher than the maximum allowed value (2^256-1).`,\n {\n cause,\n },\n )\n }\n}\n\nexport type FeeCapTooLowErrorType = FeeCapTooLowError & {\n name: 'FeeCapTooLowError'\n}\nexport class FeeCapTooLowError extends BaseError {\n static nodeMessage =\n /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/\n override name = 'FeeCapTooLow'\n constructor({\n cause,\n maxFeePerGas,\n }: { cause?: BaseError; maxFeePerGas?: bigint } = {}) {\n super(\n `The fee cap (\\`maxFeePerGas\\`${\n maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ''\n } gwei) cannot be lower than the block base fee.`,\n {\n cause,\n },\n )\n }\n}\n\nexport type NonceTooHighErrorType = NonceTooHighError & {\n name: 'NonceTooHighError'\n}\nexport class NonceTooHighError extends BaseError {\n static nodeMessage = /nonce too high/\n override name = 'NonceTooHighError'\n constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause },\n )\n }\n}\n\nexport type NonceTooLowErrorType = NonceTooLowError & {\n name: 'NonceTooLowError'\n}\nexport class NonceTooLowError extends BaseError {\n static nodeMessage =\n /nonce too low|transaction already imported|already known/\n override name = 'NonceTooLowError'\n constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n super(\n [\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is lower than the current nonce of the account.`,\n 'Try increasing the nonce or find the latest nonce with `getTransactionCount`.',\n ].join('\\n'),\n { cause },\n )\n }\n}\n\nexport type NonceMaxValueErrorType = NonceMaxValueError & {\n name: 'NonceMaxValueError'\n}\nexport class NonceMaxValueError extends BaseError {\n static nodeMessage = /nonce has max value/\n override name = 'NonceMaxValueError'\n constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage = /insufficient funds/\n override name = 'InsufficientFundsError'\n constructor({ cause }: { cause?: BaseError } = {}) {\n super(\n [\n 'The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.',\n ].join('\\n'),\n {\n cause,\n metaMessages: [\n 'This error could arise when the account does not have enough funds to:',\n ' - pay for the total gas fee,',\n ' - pay for the value to send.',\n ' ',\n 'The cost of the transaction is calculated as `gas * gas fee + value`, where:',\n ' - `gas` is the amount of gas needed for transaction to execute,',\n ' - `gas fee` is the gas fee,',\n ' - `value` is the amount of ether to send to the recipient.',\n ],\n },\n )\n }\n}\n\nexport type IntrinsicGasTooHighErrorType = IntrinsicGasTooHighError & {\n name: 'IntrinsicGasTooHighError'\n}\nexport class IntrinsicGasTooHighError extends BaseError {\n static nodeMessage = /intrinsic gas too high|gas limit reached/\n override name = 'IntrinsicGasTooHighError'\n constructor({ cause, gas }: { cause?: BaseError; gas?: bigint } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction exceeds the limit allowed for the block.`,\n {\n cause,\n },\n )\n }\n}\n\nexport type IntrinsicGasTooLowErrorType = IntrinsicGasTooLowError & {\n name: 'IntrinsicGasTooLowError'\n}\nexport class IntrinsicGasTooLowError extends BaseError {\n static nodeMessage = /intrinsic gas too low/\n override name = 'IntrinsicGasTooLowError'\n constructor({ cause, gas }: { cause?: BaseError; gas?: bigint } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n },\n )\n }\n}\n\nexport type TransactionTypeNotSupportedErrorType =\n TransactionTypeNotSupportedError & {\n name: 'TransactionTypeNotSupportedError'\n }\nexport class TransactionTypeNotSupportedError extends BaseError {\n static nodeMessage = /transaction type not valid/\n override name = 'TransactionTypeNotSupportedError'\n constructor({ cause }: { cause?: BaseError }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n })\n }\n}\n\nexport type TipAboveFeeCapErrorType = TipAboveFeeCapError & {\n name: 'TipAboveFeeCapError'\n}\nexport class TipAboveFeeCapError extends BaseError {\n static nodeMessage =\n /max priority fee per gas higher than max fee per gas|tip higher than fee cap/\n override name = 'TipAboveFeeCapError'\n constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError\n maxPriorityFeePerGas?: bigint\n maxFeePerGas?: bigint\n } = {}) {\n super(\n [\n `The provided tip (\\`maxPriorityFeePerGas\\`${\n maxPriorityFeePerGas\n ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`\n : ''\n }) cannot be higher than the fee cap (\\`maxFeePerGas\\`${\n maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''\n }).`,\n ].join('\\n'),\n {\n cause,\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n override name = 'UnknownNodeError'\n\n constructor({ cause }: { cause?: BaseError }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n })\n }\n}\n","import { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type HttpRequestErrorType = HttpRequestError & {\n name: 'HttpRequestError'\n}\nexport class HttpRequestError extends BaseError {\n override name = 'HttpRequestError'\n\n body?: { [x: string]: unknown } | { [y: string]: unknown }[]\n headers?: Headers\n status?: number\n url: string\n\n constructor({\n body,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[]\n details?: string\n headers?: Headers\n status?: number\n url: string\n }) {\n super('HTTP request failed.', {\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n })\n this.body = body\n this.headers = headers\n this.status = status\n this.url = url\n }\n}\n\nexport type WebSocketRequestErrorType = WebSocketRequestError & {\n name: 'WebSocketRequestError'\n}\nexport class WebSocketRequestError extends BaseError {\n override name = 'WebSocketRequestError'\n\n constructor({\n body,\n details,\n url,\n }: {\n body: { [key: string]: unknown }\n details: string\n url: string\n }) {\n super('WebSocket request failed.', {\n details,\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n override name = 'RpcRequestError'\n\n code: number\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; message: string }\n url: string\n }) {\n super('RPC Request failed.', {\n cause: error as any,\n details: error.message,\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n })\n this.code = error.code\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n override name = 'TimeoutError'\n\n constructor({\n body,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n url: string\n }) {\n super('The request took too long to respond.', {\n details: 'The request timed out.',\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n })\n }\n}\n","import type { Account } from '../accounts/types.js'\nimport type { SendTransactionParameters } from '../actions/wallet/sendTransaction.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hash, Hex } from '../types/misc.js'\nimport type { TransactionType } from '../types/transaction.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\n\nexport function prettyPrint(\n args: Record,\n) {\n const entries = Object.entries(args)\n .map(([key, value]) => {\n if (value === undefined || value === false) return null\n return [key, value]\n })\n .filter(Boolean) as [string, string][]\n const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0)\n return entries\n .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)\n .join('\\n')\n}\n\nexport type FeeConflictErrorType = FeeConflictError & {\n name: 'FeeConflictError'\n}\nexport class FeeConflictError extends BaseError {\n override name = 'FeeConflictError'\n constructor() {\n super(\n [\n 'Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.',\n 'Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.',\n ].join('\\n'),\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n override name = 'InvalidLegacyVError'\n\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`)\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\n override name = 'InvalidSerializableTransactionError'\n\n constructor({ transaction }: { transaction: Record }) {\n super('Cannot infer a transaction type from provided transaction.', {\n metaMessages: [\n 'Provided Transaction:',\n '{',\n prettyPrint(transaction),\n '}',\n '',\n 'To infer the type, either provide:',\n '- a `type` to the Transaction, or',\n '- an EIP-1559 Transaction with `maxFeePerGas`, or',\n '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n override name = 'InvalidSerializedTransactionType'\n\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`)\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\n override name = 'InvalidSerializedTransactionError'\n\n serializedTransaction: Hex\n type: TransactionType\n\n constructor({\n attributes,\n serializedTransaction,\n type,\n }: {\n attributes: Record\n serializedTransaction: Hex\n type: TransactionType\n }) {\n const missing = Object.entries(attributes)\n .map(([key, value]) => (typeof value === 'undefined' ? key : undefined))\n .filter(Boolean)\n super(`Invalid serialized transaction of type \"${type}\" was provided.`, {\n metaMessages: [\n `Serialized Transaction: \"${serializedTransaction}\"`,\n missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n ].filter(Boolean),\n })\n\n this.serializedTransaction = serializedTransaction\n this.type = type\n }\n}\n\nexport type InvalidStorageKeySizeErrorType = InvalidStorageKeySizeError & {\n name: 'InvalidStorageKeySizeError'\n}\nexport class InvalidStorageKeySizeError extends BaseError {\n override name = 'InvalidStorageKeySizeError'\n\n constructor({ storageKey }: { storageKey: Hex }) {\n super(\n `Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Math.floor(\n (storageKey.length - 2) / 2,\n )} bytes.`,\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\n\n override name = 'TransactionExecutionError'\n\n constructor(\n cause: BaseError,\n {\n account,\n docsPath,\n chain,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n }: Omit & {\n account: Account\n chain?: Chain\n docsPath?: string\n },\n ) {\n const prettyArgs = prettyPrint({\n chain: chain && `${chain?.name} (id: ${chain?.id})`,\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Request Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n override name = 'TransactionNotFoundError'\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash\n blockNumber?: bigint\n blockTag?: BlockTag\n hash?: Hash\n index?: number\n }) {\n let identifier = 'Transaction'\n if (blockTag && index !== undefined)\n identifier = `Transaction at block time \"${blockTag}\" at index \"${index}\"`\n if (blockHash && index !== undefined)\n identifier = `Transaction at block hash \"${blockHash}\" at index \"${index}\"`\n if (blockNumber && index !== undefined)\n identifier = `Transaction at block number \"${blockNumber}\" at index \"${index}\"`\n if (hash) identifier = `Transaction with hash \"${hash}\"`\n super(`${identifier} could not be found.`)\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\n override name = 'TransactionReceiptNotFoundError'\n constructor({ hash }: { hash: Hash }) {\n super(\n `Transaction receipt with hash \"${hash}\" could not be found. The Transaction may not be processed on a block yet.`,\n )\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n override name = 'WaitForTransactionReceiptTimeoutError'\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n )\n }\n}\n","export const version = '1.19.10'\n","import type { Address } from 'abitype'\n\nimport { version } from './version.js'\n\nexport type ErrorType = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\nexport const getVersion = () => `viem@${version}`\n","import type {\n AbiParameter,\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from '../encoding/fromHex.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type GetArrayComponentsErrorType,\n getArrayComponents,\n} from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n TParams extends\n | readonly AbiParameter[]\n | readonly unknown[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n TParams extends readonly AbiParameter[] ? TParams : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiDecodingZeroDataErrorType\n | DecodeParamsErrorType\n | SizeErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const TParams extends readonly AbiParameter[] | readonly unknown[],\n>(params: TParams, data: Hex): DecodeAbiParametersReturnType {\n if (data === '0x' && (params as unknown[]).length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data,\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n return decodeParams({\n data,\n params: params as readonly AbiParameter[],\n }) as unknown as DecodeAbiParametersReturnType\n}\n\n////////////////////////////////////////////////////////////////////\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeParamsErrorType = DecodeParamErrorType | SizeErrorType | ErrorType\n\nfunction decodeParams({\n data,\n params,\n}: { data: Hex; params: TParams }) {\n const decodedValues: unknown[] = []\n let position = 0\n\n for (let i = 0; i < params.length; i++) {\n if (position >= size(data))\n throw new AbiDecodingDataSizeTooSmallError({\n data,\n params,\n size: size(data),\n })\n\n const param = params[i]\n const { consumed, value } = decodeParam({ data, param, position })\n decodedValues.push(value)\n // Step across the data by the amount of data consumed by this parameter.\n position += consumed\n }\n\n return decodedValues as unknown as AbiParametersToPrimitiveTypes\n}\n\ntype DecodeParamErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeStringErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | InvalidAbiDecodingTypeErrorType\n | ErrorType\n\nfunction decodeParam({\n data,\n param,\n position,\n}: { data: Hex; param: AbiParameter; position: number }): {\n consumed: number\n value: any\n} {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(data, {\n length,\n param: { ...param, type: type } as AbiParameter,\n position,\n })\n }\n if (param.type === 'tuple') {\n return decodeTuple(data, { param: param as TupleAbiParameter, position })\n }\n if (param.type === 'string') {\n return decodeString(data, { position })\n }\n if (param.type.startsWith('bytes')) {\n return decodeBytes(data, { param, position })\n }\n\n const value = slice(data, position, position + 32, { strict: true }) as Hex\n if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n return decodeNumber(value, { param })\n }\n if (param.type === 'address') {\n return decodeAddress(value)\n }\n if (param.type === 'bool') {\n return decodeBool(value)\n }\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | SliceErrorType\n | ErrorType\n\nfunction decodeAddress(value: Hex) {\n return { consumed: 32, value: checksumAddress(slice(value, -20)) }\n}\n\ntype DecodeArrayErrorType = HexToNumberErrorType | SliceErrorType | ErrorType\n\nfunction decodeArray(\n data: Hex,\n {\n param,\n length,\n position,\n }: {\n param: TParam\n length: number | null\n position: number\n },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // we will need to decode the offset of the array data.\n if (!length) {\n // Get the offset of the array data.\n const offset = hexToNumber(\n slice(data, position, position + 32, { strict: true }),\n )\n // Get the length of the array from the offset.\n const length = hexToNumber(\n slice(data, offset, offset + 32, { strict: true }),\n )\n\n let consumed = 0\n const value: AbiParameterToPrimitiveType[] = []\n for (let i = 0; i < length; ++i) {\n const decodedChild = decodeParam({\n data: slice(data, offset + 32),\n param,\n position: consumed,\n })\n consumed += decodedChild.consumed\n value.push(decodedChild.value)\n }\n return { value, consumed: 32 }\n }\n\n // If the length of the array is known in advance,\n // and the length of an element deeply nested in the array is not known,\n // we need to decode the offset of the array data.\n if (hasDynamicChild(param)) {\n // Get the child type of the array.\n const arrayComponents = getArrayComponents(param.type)\n // If the child type is not known, the array is dynamic.\n const dynamicChild = !arrayComponents?.[0]\n\n let consumed = 0\n const value: AbiParameterToPrimitiveType[] = []\n for (let i = 0; i < length; ++i) {\n const offset = hexToNumber(\n slice(data, position, position + 32, { strict: true }),\n )\n const decodedChild = decodeParam({\n data: slice(data, offset),\n param,\n position: dynamicChild ? consumed : i * 32,\n })\n consumed += decodedChild.consumed\n value.push(decodedChild.value)\n }\n return { value, consumed: 32 }\n }\n\n // If the length of the array is known in advance,\n // and the length of each element in the array is known,\n // the array data is encoded contiguously after the array.\n let consumed = 0\n const value: AbiParameterToPrimitiveType[] = []\n for (let i = 0; i < length; ++i) {\n const decodedChild = decodeParam({\n data,\n param,\n position: position + consumed,\n })\n consumed += decodedChild.consumed\n value.push(decodedChild.value)\n }\n return { value, consumed }\n}\n\ntype DecodeBoolErrorType = HexToBoolErrorType | ErrorType\n\nfunction decodeBool(value: Hex) {\n return { consumed: 32, value: hexToBool(value) }\n}\n\ntype DecodeBytesErrorType = HexToNumberErrorType | SliceErrorType | ErrorType\n\nfunction decodeBytes(\n data: Hex,\n { param, position }: { param: TParam; position: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // If we don't have a size, we're dealing with a dynamic-size array\n // so we need to read the offset of the data part first.\n const offset = hexToNumber(\n slice(data, position, position + 32, { strict: true }),\n )\n const length = hexToNumber(\n slice(data, offset, offset + 32, { strict: true }),\n )\n // If there is no length, we have zero data.\n if (length === 0) return { consumed: 32, value: '0x' }\n const value = slice(data, offset + 32, offset + 32 + length, {\n strict: true,\n })\n return { consumed: 32, value }\n }\n\n const value = slice(data, position, position + parseInt(size), {\n strict: true,\n })\n return { consumed: 32, value }\n}\n\ntype DecodeNumberErrorType =\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | ErrorType\n\nfunction decodeNumber(\n value: Hex,\n { param }: { param: TParam },\n) {\n const signed = param.type.startsWith('int')\n const size = parseInt(param.type.split('int')[1] || '256')\n return {\n consumed: 32,\n value:\n size > 48\n ? hexToBigInt(value, { signed })\n : hexToNumber(value, { signed }),\n }\n}\n\ntype DecodeStringErrorType =\n | HexToNumberErrorType\n | HexToStringErrorType\n | SliceErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(data: Hex, { position }: { position: number }) {\n const offset = hexToNumber(\n slice(data, position, position + 32, { strict: true }),\n )\n const length = hexToNumber(slice(data, offset, offset + 32, { strict: true }))\n // If there is no length, we have zero data (empty string).\n if (length === 0) return { consumed: 32, value: '' }\n const value = hexToString(\n trim(slice(data, offset + 32, offset + 32 + length, { strict: true })),\n )\n return { consumed: 32, value }\n}\n\ntype DecodeTupleErrorType =\n | HasDynamicChildErrorType\n | HexToNumberErrorType\n | SliceErrorType\n | ErrorType\n\nfunction decodeTuple<\n const TParam extends AbiParameter & { components: readonly AbiParameter[] },\n>(data: Hex, { param, position }: { param: TParam; position: number }) {\n // Tuples can have unnamed components (i.e. they are arrays), so we must\n // determine whether the tuple is named or unnamed. In the case of a named\n // tuple, the value will be an object where each property is the name of the\n // component. In the case of an unnamed tuple, the value will be an array.\n const hasUnnamedChild =\n param.components.length === 0 || param.components.some(({ name }) => !name)\n\n // Initialize the value to an object or an array, depending on whether the\n // tuple is named or unnamed.\n const value: any = hasUnnamedChild ? [] : {}\n let consumed = 0\n\n // If the tuple has a dynamic child, we must first decode the offset to the\n // tuple data.\n if (hasDynamicChild(param)) {\n const offset = hexToNumber(\n slice(data, position, position + 32, { strict: true }),\n )\n // Decode each component of the tuple, starting at the offset.\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n const decodedChild = decodeParam({\n data: slice(data, offset),\n param: component,\n position: consumed,\n })\n consumed += decodedChild.consumed\n value[hasUnnamedChild ? i : component?.name!] = decodedChild.value\n }\n return { consumed: 32, value }\n }\n\n // If the tuple has static children, we can just decode each component\n // in sequence.\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n const decodedChild = decodeParam({\n data,\n param: component,\n position: position + consumed,\n })\n consumed += decodedChild.consumed\n value[hasUnnamedChild ? i : component?.name!] = decodedChild.value\n }\n return { consumed, value }\n}\n\ntype HasDynamicChildErrorType = GetArrayComponentsErrorType | ErrorType\n\nfunction hasDynamicChild(param: AbiParameter) {\n const { type } = param\n if (type === 'string') return true\n if (type === 'bytes') return true\n if (type.endsWith('[]')) return true\n\n if (type === 'tuple') return (param as any).components?.some(hasDynamicChild)\n\n const arrayComponents = getArrayComponents(param.type)\n if (\n arrayComponents &&\n hasDynamicChild({ ...param, type: arrayComponents[1] } as AbiParameter)\n )\n return true\n\n return false\n}\n","import type { Abi, ExtractAbiError, ExtractAbiErrorNames } from 'abitype'\n\nimport { solidityError, solidityPanic } from '../../constants/solidity.js'\nimport {\n AbiDecodingZeroDataError,\n type AbiDecodingZeroDataErrorType,\n AbiErrorSignatureNotFoundError,\n type AbiErrorSignatureNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { AbiItem, GetErrorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { slice } from '../data/slice.js'\nimport {\n type GetFunctionSelectorErrorType,\n getFunctionSelector,\n} from '../hash/getFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n TAbi extends Abi | readonly unknown[] = Abi,\n> = { abi?: TAbi; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n TAbi extends Abi | readonly unknown[] = Abi,\n _ErrorNames extends string = TAbi extends Abi\n ? Abi extends TAbi\n ? string\n : ExtractAbiErrorNames\n : string,\n> = {\n [TName in _ErrorNames]: {\n abiItem: TAbi extends Abi ? ExtractAbiError : AbiItem\n args: GetErrorArgs['args']\n errorName: TName\n }\n}[_ErrorNames]\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult({\n abi,\n data,\n}: DecodeErrorResultParameters): DecodeErrorResultReturnType {\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...((abi as Abi) || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === getFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args: ('inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined) as readonly unknown[] | undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType\n}\n","import type { Abi, ExtractAbiFunctionNames } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n AbiItem,\n ContractFunctionResult,\n GetFunctionArgs,\n InferFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n TAbi extends Abi | readonly unknown[] = Abi,\n TFunctionName extends string | undefined = string,\n _FunctionName = InferFunctionName,\n> = {\n functionName?: _FunctionName\n data: Hex\n} & (TFunctionName extends string\n ? { abi: TAbi } & Partial>\n : _FunctionName extends string\n ? { abi: [TAbi[number]] } & Partial>\n : never)\n\nexport type DecodeFunctionResultReturnType<\n TAbi extends Abi | readonly unknown[] = Abi,\n TFunctionName extends string | undefined = string,\n _FunctionName extends string = TAbi extends Abi\n ? Abi extends TAbi\n ? string\n : ExtractAbiFunctionNames[number]\n : string,\n> = TFunctionName extends string\n ? ContractFunctionResult\n : ContractFunctionResult\n\nexport type DecodeFunctionResultErrorType =\n | AbiFunctionNotFoundErrorType\n | AbiFunctionOutputsNotFoundErrorType\n | DecodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function decodeFunctionResult<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends string | undefined = undefined,\n>({\n abi,\n args,\n functionName,\n data,\n}: DecodeFunctionResultParameters<\n TAbi,\n TFunctionName\n>): DecodeFunctionResultReturnType {\n let abiItem = abi[0] as AbiItem\n if (functionName) {\n abiItem = getAbiItem({\n abi,\n args,\n name: functionName,\n } as GetAbiItemParameters)\n if (!abiItem) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n const values = decodeAbiParameters(abiItem.outputs, data)\n if (values && values.length > 1) return values as any\n if (values && values.length === 1) return values[0] as any\n return undefined as any\n}\n","import type {\n AbiParameter,\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\n\nimport {\n AbiEncodingArrayLengthMismatchError,\n type AbiEncodingArrayLengthMismatchErrorType,\n AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\n InvalidAbiEncodingTypeError,\n type InvalidAbiEncodingTypeErrorType,\n InvalidArrayError,\n type InvalidArrayErrorType,\n} from '../../errors/abi.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { type PadHexErrorType, padHex } from '../data/pad.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n type BoolToHexErrorType,\n type NumberToHexErrorType,\n type StringToHexErrorType,\n boolToHex,\n numberToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type EncodeAbiParametersReturnType = Hex\n\nexport type EncodeAbiParametersErrorType =\n | AbiEncodingLengthMismatchErrorType\n | PrepareParamsErrorType\n | EncodeParamsErrorType\n | ErrorType\n\n/**\n * @description Encodes a list of primitive values into an ABI-encoded hex value.\n */\nexport function encodeAbiParameters<\n const TParams extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: TParams,\n values: TParams extends readonly AbiParameter[]\n ? AbiParametersToPrimitiveTypes\n : never,\n): EncodeAbiParametersReturnType {\n if (params.length !== values.length)\n throw new AbiEncodingLengthMismatchError({\n expectedLength: params.length as number,\n givenLength: values.length,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values,\n })\n const data = encodeParams(preparedParams)\n if (data.length === 0) return '0x'\n return data\n}\n\n/////////////////////////////////////////////////////////////////\n\ntype PreparedParam = { dynamic: boolean; encoded: Hex }\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\ntype Tuple = AbiParameterToPrimitiveType\n\nexport type PrepareParamsErrorType = ErrorType\n\nfunction prepareParams({\n params,\n values,\n}: {\n params: TParams\n values: AbiParametersToPrimitiveTypes\n}) {\n const preparedParams: PreparedParam[] = []\n for (let i = 0; i < params.length; i++) {\n preparedParams.push(prepareParam({ param: params[i], value: values[i] }))\n }\n return preparedParams\n}\n\nexport type PrepareParamErrorType =\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam({\n param,\n value,\n}: {\n param: TParam\n value: AbiParameterToPrimitiveType\n}): PreparedParam {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, { length, param: { ...param, type } })\n }\n if (param.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n param: param as TupleAbiParameter,\n })\n }\n if (param.type === 'address') {\n return encodeAddress(value as unknown as Hex)\n }\n if (param.type === 'bool') {\n return encodeBool(value as unknown as boolean)\n }\n if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n const signed = param.type.startsWith('int')\n return encodeNumber(value as unknown as number, { signed })\n }\n if (param.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex, { param })\n }\n if (param.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new InvalidAbiEncodingTypeError(param.type, {\n docsPath: '/docs/contract/encodeAbiParameters',\n })\n}\n\n/////////////////////////////////////////////////////////////////\n\nexport type EncodeParamsErrorType =\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeParams(preparedParams: PreparedParam[]): Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i]\n if (dynamic) staticSize += 32\n else staticSize += size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParams: Hex[] = []\n const dynamicParams: Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i]\n if (dynamic) {\n staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }))\n dynamicParams.push(encoded)\n dynamicSize += size(encoded)\n } else {\n staticParams.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return concat([...staticParams, ...dynamicParams])\n}\n\n/////////////////////////////////////////////////////////////////\n\nexport type EncodeAddressErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nfunction encodeAddress(value: Hex): PreparedParam {\n if (!isAddress(value)) throw new InvalidAddressError({ address: value })\n return { dynamic: false, encoded: padHex(value.toLowerCase() as Hex) }\n}\n\nexport type EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray(\n value: AbiParameterToPrimitiveType,\n {\n length,\n param,\n }: {\n length: number | null\n param: TParam\n },\n): PreparedParam {\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiEncodingArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${param.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParams: PreparedParam[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParam({ param, value: value[i] })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParams.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encodeParams(preparedParams)\n if (dynamic) {\n const length = numberToHex(preparedParams.length, { size: 32 })\n return {\n dynamic: true,\n encoded: preparedParams.length > 0 ? concat([length, data]) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: concat(preparedParams.map(({ encoded }) => encoded)),\n }\n}\n\nexport type EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes(\n value: Hex,\n { param }: { param: TParam },\n): PreparedParam {\n const [, paramSize] = param.type.split('bytes')\n const bytesSize = size(value)\n if (!paramSize) {\n let value_ = value\n // If the size is not divisible by 32 bytes, pad the end\n // with empty bytes to the ceiling 32 bytes.\n if (bytesSize % 32 !== 0)\n value_ = padHex(value_, {\n dir: 'right',\n size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n })\n return {\n dynamic: true,\n encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),\n }\n }\n if (bytesSize !== parseInt(paramSize))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: parseInt(paramSize),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\nexport type EncodeBoolErrorType =\n | PadHexErrorType\n | BoolToHexErrorType\n | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\nexport type EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed }: { signed: boolean },\n): PreparedParam {\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\nexport type EncodeStringErrorType =\n | ConcatErrorType\n | NumberToHexErrorType\n | PadHexErrorType\n | SizeErrorType\n | SliceErrorType\n | StringToHexErrorType\n | ErrorType\n\nfunction encodeString(value: string): PreparedParam {\n const hexValue = stringToHex(value)\n const partsLength = Math.ceil(size(hexValue) / 32)\n const parts: Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(\n padHex(slice(hexValue, i * 32, (i + 1) * 32), {\n dir: 'right',\n }),\n )\n }\n return {\n dynamic: true,\n encoded: concat([\n padHex(numberToHex(size(hexValue), { size: 32 })),\n ...parts,\n ]),\n }\n}\n\nexport type EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const TParam extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType,\n { param }: { param: TParam },\n): PreparedParam {\n let dynamic = false\n const preparedParams: PreparedParam[] = []\n for (let i = 0; i < param.components.length; i++) {\n const param_ = param.components[i]\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParam({\n param: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParams.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encodeParams(preparedParams)\n : concat(preparedParams.map(({ encoded }) => encoded)),\n }\n}\n\nexport type GetArrayComponentsErrorType = ErrorType\n\nexport function getArrayComponents(\n type: string,\n): [length: number | null, innerType: string] | undefined {\n const matches = type.match(/^(.*)\\[(\\d+)?\\]$/)\n return matches\n ? // Return `null` if the array is dynamic.\n [matches[2] ? Number(matches[2]) : null, matches[1]]\n : undefined\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n AbiItem,\n GetFunctionArgs,\n InferFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type GetFunctionSelectorErrorType,\n getFunctionSelector,\n} from '../hash/getFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './getAbiItem.js'\n\nexport type EncodeFunctionDataParameters<\n TAbi extends Abi | readonly unknown[] = Abi,\n TFunctionName extends string | undefined = string,\n _FunctionName = InferFunctionName,\n> = {\n functionName?: _FunctionName\n} & (TFunctionName extends string\n ? { abi: TAbi } & GetFunctionArgs\n : _FunctionName extends string\n ? { abi: [TAbi[number]] } & GetFunctionArgs\n : never)\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | GetFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends string | undefined = undefined,\n>({\n abi,\n args,\n functionName,\n}: EncodeFunctionDataParameters) {\n let abiItem = abi[0] as AbiItem\n if (functionName) {\n abiItem = getAbiItem({\n abi,\n args,\n name: functionName,\n } as GetAbiItemParameters)\n if (!abiItem)\n throw new AbiFunctionNotFoundError(functionName, {\n docsPath: '/docs/contract/encodeFunctionData',\n })\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, {\n docsPath: '/docs/contract/encodeFunctionData',\n })\n\n const definition = formatAbiItem(abiItem)\n const signature = getFunctionSelector(definition)\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, (args ?? []) as readonly unknown[])\n : undefined\n return concatHex([signature, data ?? '0x'])\n}\n","import type { AbiParameter } from 'abitype'\n\nimport {\n InvalidDefinitionTypeError,\n type InvalidDefinitionTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\n\nexport type FormatAbiItemErrorType =\n | FormatAbiParamsErrorType\n | InvalidDefinitionTypeErrorType\n | ErrorType\n\nexport function formatAbiItem(\n abiItem: AbiItem,\n { includeName = false }: { includeName?: boolean } = {},\n) {\n if (\n abiItem.type !== 'function' &&\n abiItem.type !== 'event' &&\n abiItem.type !== 'error'\n )\n throw new InvalidDefinitionTypeError(abiItem.type)\n\n return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`\n}\n\nexport type FormatAbiParamsErrorType = ErrorType\n\nexport function formatAbiParams(\n params: readonly AbiParameter[] | undefined,\n { includeName = false }: { includeName?: boolean } = {},\n): string {\n if (!params) return ''\n return params\n .map((param) => formatAbiParam(param, { includeName }))\n .join(includeName ? ', ' : ',')\n}\n\nexport type FormatAbiParamErrorType = ErrorType\n\nfunction formatAbiParam(\n param: AbiParameter,\n { includeName }: { includeName: boolean },\n): string {\n if (param.type.startsWith('tuple')) {\n return `(${formatAbiParams(\n (param as unknown as { components: AbiParameter[] }).components,\n { includeName },\n )})${param.type.slice('tuple'.length)}`\n }\n return param.type + (includeName && param.name ? ` ${param.name}` : '')\n}\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetFunctionArgs, InferItemName } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { getEventSelector } from '../../utils/hash/getEventSelector.js'\nimport {\n type GetFunctionSelectorErrorType,\n getFunctionSelector,\n} from '../../utils/hash/getFunctionSelector.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\n\nexport type GetAbiItemParameters<\n TAbi extends Abi | readonly unknown[] = Abi,\n TItemName extends string = string,\n> = {\n abi: TAbi\n name: InferItemName | Hex\n} & Partial>\n\nexport type GetAbiItemReturnType<\n TAbi extends Abi | readonly unknown[] = Abi,\n TItemName extends string = string,\n> = Extract<\n TAbi[number],\n {\n name: TItemName\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | GetFunctionSelectorErrorType\n | ErrorType\n\nexport function getAbiItem<\n const TAbi extends Abi | readonly unknown[],\n TItemName extends string,\n>({\n abi,\n args = [],\n name,\n}: GetAbiItemParameters): GetAbiItemReturnType<\n TAbi,\n TItemName\n> {\n const isSelector = isHex(name, { strict: false })\n\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return getFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return getEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) return undefined as any\n if (abiItems.length === 1) return abiItems[0] as any\n\n for (const abiItem of abiItems) {\n if (!('inputs' in abiItem)) continue\n if (!args || args.length === 0) {\n if (!abiItem.inputs || abiItem.inputs.length === 0) return abiItem as any\n continue\n }\n if (!abiItem.inputs) continue\n if (abiItem.inputs.length === 0) continue\n if (abiItem.inputs.length !== args.length) continue\n const matched = (args as readonly unknown[]).every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, abiParameter as AbiParameter)\n })\n if (matched) return abiItem as any\n }\n return abiItems[0] as any\n}\n\nexport type IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\nexport function isArgOfType(arg: unknown, abiParameter: AbiParameter): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return isAddress(arg as Address)\n case 'bool':\n return argType === 'boolean'\n case 'function':\n return argType === 'string'\n case 'string':\n return argType === 'string'\n default: {\n if (abiParameterType === 'tuple' && 'components' in abiParameter)\n return Object.values(abiParameter.components).every(\n (component, index) => {\n return isArgOfType(\n Object.values(arg as unknown[] | Record)[index],\n component as AbiParameter,\n )\n },\n )\n\n // `(u)int`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n // https://regexr.com/6v8hp\n if (\n /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(\n abiParameterType,\n )\n )\n return argType === 'number' || argType === 'bigint'\n\n // `bytes`: binary type of `M` bytes, `0 < M <= 32`\n // https://regexr.com/6va55\n if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))\n return argType === 'string' || arg instanceof Uint8Array\n\n // fixed-length (`[M]`) and dynamic (`[]`) arrays\n // https://regexr.com/6va6i\n if (/[a-z]+[1-9]{0,3}(\\[[0-9]{0,}\\])+$/.test(abiParameterType)) {\n return (\n Array.isArray(arg) &&\n arg.every((x: unknown) =>\n isArgOfType(x, {\n ...abiParameter,\n // Pop off `[]` or `[M]` from end of type\n type: abiParameterType.replace(/(\\[[0-9]{0,}\\])$/, ''),\n } as AbiParameter),\n )\n )\n }\n\n return false\n }\n }\n}\n","import type { Address } from 'abitype'\n\nimport { InvalidAddressError } from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(address_: Address, chainId?: number): Address {\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase()\n const hash = keccak256(stringToBytes(hexAddress), 'bytes')\n\n const address = (\n chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress\n ).split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase()\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase()\n }\n }\n\n return `0x${address.join('')}`\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(address: string, chainId?: number): Address {\n if (!isAddress(address)) throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(address: string): address is Address {\n return addressRegex.test(address)\n}\n","import {\n ChainDoesNotSupportContract,\n type ChainDoesNotSupportContractErrorType,\n} from '../../errors/chain.js'\nimport type { Chain, ChainContract } from '../../types/chain.js'\n\nexport type GetChainContractAddressErrorType =\n ChainDoesNotSupportContractErrorType\n\nexport function getChainContractAddress({\n blockNumber,\n chain,\n contract: name,\n}: {\n blockNumber?: bigint\n chain: Chain\n contract: string\n}) {\n const contract = (chain?.contracts as Record)?.[name]\n if (!contract)\n throw new ChainDoesNotSupportContract({\n chain,\n contract: { name },\n })\n\n if (\n blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber\n )\n throw new ChainDoesNotSupportContract({\n blockNumber,\n chain,\n contract: {\n name,\n blockCreated: contract.blockCreated,\n },\n })\n\n return contract.address\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType =\n TValue extends Hex ? Hex : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat(\n values: readonly TValue[],\n): ConcatReturnType {\n if (typeof values[0] === 'string')\n return concatHex(values as readonly Hex[]) as ConcatReturnType\n return concatBytes(values as readonly ByteArray[]) as ConcatReturnType\n}\n\nexport type ConcatBytesErrorType = ErrorType\n\nexport function concatBytes(values: readonly ByteArray[]): ByteArray {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n let offset = 0\n for (const arr of values) {\n result.set(arr, offset)\n offset += arr.length\n }\n return result\n}\n\nexport type ConcatHexErrorType = ErrorType\n\nexport function concatHex(values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce(\n (acc, x) => acc + x.replace('0x', ''),\n '',\n )}`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type IsHexErrorType = ErrorType\n\nexport function isHex(\n value: unknown,\n { strict = true }: { strict?: boolean } = {},\n): value is Hex {\n if (!value) return false\n if (typeof value !== 'string') return false\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x')\n}\n","import {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype PadOptions = {\n dir?: 'left' | 'right'\n size?: number | null\n}\nexport type PadReturnType = TValue extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: TValue,\n { dir, size = 32 }: PadOptions = {},\n): PadReturnType {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size }) as PadReturnType\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType\n}\n\nexport type PadHexErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padHex(hex_: Hex, { dir, size = 32 }: PadOptions = {}) {\n if (size === null) return hex_\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](\n size * 2,\n '0',\n )}` as Hex\n}\n\nexport type PadBytesErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padBytes(\n bytes: ByteArray,\n { dir, size = 32 }: PadOptions = {},\n) {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\n\nexport type SizeErrorType = IsHexErrorType | ErrorType\n\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value: Hex | ByteArray) {\n if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2)\n return value.length\n}\n","import {\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\nimport { type SizeErrorType, size } from './size.js'\n\nexport type SliceReturnType = TValue extends Hex\n ? Hex\n : ByteArray\n\nexport type SliceErrorType =\n | IsHexErrorType\n | SliceBytesErrorType\n | SliceHexErrorType\n | ErrorType\n\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice(\n value: TValue,\n start?: number,\n end?: number,\n { strict }: { strict?: boolean } = {},\n): SliceReturnType {\n if (isHex(value, { strict: false }))\n return sliceHex(value as Hex, start, end, {\n strict,\n }) as SliceReturnType\n return sliceBytes(value as ByteArray, start, end, {\n strict,\n }) as SliceReturnType\n}\n\nexport type AssertStartOffsetErrorType =\n | SliceOffsetOutOfBoundsErrorType\n | SizeErrorType\n | ErrorType\n\nfunction assertStartOffset(value: Hex | ByteArray, start?: number) {\n if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n throw new SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: size(value),\n })\n}\n\nexport type AssertEndOffsetErrorType =\n | SliceOffsetOutOfBoundsErrorType\n | SizeErrorType\n | ErrorType\n\nfunction assertEndOffset(value: Hex | ByteArray, start?: number, end?: number) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n size(value) !== end - start\n ) {\n throw new SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: size(value),\n })\n }\n}\n\nexport type SliceBytesErrorType =\n | AssertStartOffsetErrorType\n | AssertEndOffsetErrorType\n | ErrorType\n\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(\n value_: ByteArray,\n start?: number,\n end?: number,\n { strict }: { strict?: boolean } = {},\n): ByteArray {\n assertStartOffset(value_, start)\n const value = value_.slice(start, end)\n if (strict) assertEndOffset(value, start, end)\n return value\n}\n\nexport type SliceHexErrorType =\n | AssertStartOffsetErrorType\n | AssertEndOffsetErrorType\n | ErrorType\n\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(\n value_: Hex,\n start?: number,\n end?: number,\n { strict }: { strict?: boolean } = {},\n): Hex {\n assertStartOffset(value_, start)\n const value = `0x${value_\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}` as const\n if (strict) assertEndOffset(value, start, end)\n return value\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right'\n}\nexport type TrimReturnType = TValue extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim(\n hexOrBytes: TValue,\n { dir = 'left' }: TrimOptions = {},\n): TrimReturnType {\n let data: any =\n typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes\n\n let sliceLength = 0\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++\n else break\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength)\n\n if (typeof hexOrBytes === 'string') {\n if (data.length === 1 && dir === 'right') data = `${data}0`\n return `0x${\n data.length % 2 === 1 ? `0${data}` : data\n }` as TrimReturnType\n }\n return data as TrimReturnType\n}\n","import {\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type SizeErrorType, size as size_ } from '../data/size.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\n\nexport type AssertSizeErrorType =\n | SizeOverflowErrorType\n | SizeErrorType\n | ErrorType\n\nexport function assertSize(\n hexOrBytes: Hex | ByteArray,\n { size }: { size: number },\n): void {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n })\n}\n\nexport type FromHexParameters<\n TTo extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | TTo\n | {\n /** Size (in bytes) of the hex value. */\n size?: number\n /** Type to convert to. */\n to: TTo\n }\n\nexport type FromHexReturnType = TTo extends 'string'\n ? string\n : TTo extends 'bigint'\n ? bigint\n : TTo extends 'number'\n ? number\n : TTo extends 'bytes'\n ? ByteArray\n : TTo extends 'boolean'\n ? boolean\n : never\n\nexport type FromHexErrorType =\n | HexToNumberErrorType\n | HexToBigIntErrorType\n | HexToBoolErrorType\n | HexToStringErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html\n * - Example: https://viem.sh/docs/utilities/fromHex.html#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex<\n TTo extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n>(hex: Hex, toOrOpts: FromHexParameters): FromHexReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number') return hexToNumber(hex, opts) as FromHexReturnType\n if (to === 'bigint') return hexToBigInt(hex, opts) as FromHexReturnType\n if (to === 'string') return hexToString(hex, opts) as FromHexReturnType\n if (to === 'boolean') return hexToBool(hex, opts) as FromHexReturnType\n return hexToBytes(hex, opts) as FromHexReturnType\n}\n\nexport type HexToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean\n /** Size (in bytes) of the hex value. */\n size?: number\n}\n\nexport type HexToBigIntErrorType = AssertSizeErrorType | ErrorType\n\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {\n const { signed } = opts\n\n if (opts.size) assertSize(hex, { size: opts.size })\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n\n if (value <= max) return value\n\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n\n}\n\nexport type HexToBoolOpts = {\n /** Size (in bytes) of the hex value. */\n size?: number\n}\n\nexport type HexToBoolErrorType =\n | AssertSizeErrorType\n | InvalidHexBooleanErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_: Hex, opts: HexToBoolOpts = {}): boolean {\n let hex = hex_\n if (opts.size) {\n assertSize(hex, { size: opts.size })\n hex = trim(hex)\n }\n if (trim(hex) === '0x00') return false\n if (trim(hex) === '0x01') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport type HexToNumberOpts = HexToBigIntOpts\n\nexport type HexToNumberErrorType = HexToBigIntErrorType | ErrorType\n\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex: Hex, opts: HexToNumberOpts = {}): number {\n return Number(hexToBigInt(hex, opts))\n}\n\nexport type HexToStringOpts = {\n /** Size (in bytes) of the hex value. */\n size?: number\n}\n\nexport type HexToStringErrorType =\n | AssertSizeErrorType\n | HexToBytesErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex: Hex, opts: HexToStringOpts = {}): string {\n let bytes = hexToBytes(hex)\n if (opts.size) {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\nimport {\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n} from './toHex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nexport type ToBytesParameters = {\n /** Size of the output bytes. */\n size?: number\n}\n\nexport type ToBytesErrorType =\n | NumberToBytesErrorType\n | BoolToBytesErrorType\n | HexToBytesErrorType\n | StringToBytesErrorType\n | IsHexErrorType\n | ErrorType\n\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html\n * - Example: https://viem.sh/docs/utilities/toBytes.html#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(\n value: string | bigint | number | boolean | Hex,\n opts: ToBytesParameters = {},\n): ByteArray {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts)\n if (typeof value === 'boolean') return boolToBytes(value, opts)\n if (isHex(value)) return hexToBytes(value, opts)\n return stringToBytes(value, opts)\n}\n\nexport type BoolToBytesOpts = {\n /** Size of the output bytes. */\n size?: number\n}\n\nexport type BoolToBytesErrorType =\n | AssertSizeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value: boolean, opts: BoolToBytesOpts = {}) {\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size })\n return pad(bytes, { size: opts.size })\n }\n return bytes\n}\n\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\nfunction charCodeToBase16(char: number) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10)\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10)\n return undefined\n}\n\nexport type HexToBytesOpts = {\n /** Size of the output bytes. */\n size?: number\n}\n\nexport type HexToBytesErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_: Hex, opts: HexToBytesOpts = {}): ByteArray {\n let hex = hex_\n if (opts.size) {\n assertSize(hex, { size: opts.size })\n hex = pad(hex, { dir: 'right', size: opts.size })\n }\n\n let hexString = hex.slice(2) as string\n if (hexString.length % 2) hexString = `0${hexString}`\n\n const length = hexString.length / 2\n const bytes = new Uint8Array(length)\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${\n hexString[j - 1]\n }\" in \"${hexString}\").`,\n )\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight\n }\n return bytes\n}\n\nexport type NumberToBytesErrorType =\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value: bigint | number, opts?: NumberToHexOpts) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number\n}\n\nexport type StringToBytesErrorType =\n | AssertSizeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(\n value: string,\n opts: StringToBytesOpts = {},\n): ByteArray {\n const bytes = encoder.encode(value)\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size })\n return pad(bytes, { dir: 'right', size: opts.size })\n }\n return bytes\n}\n","import {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\nexport type ToHexParameters = {\n /** The size (in bytes) of the output hex value. */\n size?: number\n}\n\nexport type ToHexErrorType =\n | BoolToHexErrorType\n | BytesToHexErrorType\n | NumberToHexErrorType\n | StringToHexErrorType\n | ErrorType\n\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html\n * - Example: https://viem.sh/docs/utilities/toHex.html#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(\n value: string | number | bigint | boolean | ByteArray,\n opts: ToHexParameters = {},\n): Hex {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts)\n if (typeof value === 'string') {\n return stringToHex(value, opts)\n }\n if (typeof value === 'boolean') return boolToHex(value, opts)\n return bytesToHex(value, opts)\n}\n\nexport type BoolToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number\n}\n\nexport type BoolToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value: boolean, opts: BoolToHexOpts = {}): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size })\n return pad(hex, { size: opts.size })\n }\n return hex\n}\n\nexport type BytesToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number\n}\n\nexport type BytesToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value: ByteArray, opts: BytesToHexOpts = {}): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]]\n }\n const hex = `0x${string}` as const\n\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size })\n return pad(hex, { dir: 'right', size: opts.size })\n }\n return hex\n}\n\nexport type NumberToHexOpts =\n | {\n /** Whether or not the number of a signed representation. */\n signed?: boolean\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: never\n /** The size (in bytes) of the output hex value. */\n size?: number\n }\n\nexport type NumberToHexErrorType =\n | IntegerOutOfRangeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(\n value_: number | bigint,\n opts: NumberToHexOpts = {},\n): Hex {\n const { signed, size } = opts\n\n const value = BigInt(value_)\n\n let maxValue\n if (size) {\n if (signed) maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n\n else maxValue = 2n ** (BigInt(size) * 8n) - 1n\n } else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER)\n }\n\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0\n\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : ''\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n })\n }\n\n const hex = `0x${(signed && value < 0\n ? (1n << BigInt(size * 8)) + BigInt(value)\n : value\n ).toString(16)}` as Hex\n if (size) return pad(hex, { size }) as Hex\n return hex\n}\n\nexport type StringToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number\n}\n\nexport type StringToHexErrorType = BytesToHexErrorType | ErrorType\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_: string, opts: StringToHexOpts = {}): Hex {\n const value = encoder.encode(value_)\n return bytesToHex(value, opts)\n}\n","import type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ExecutionRevertedError,\n type ExecutionRevertedErrorType,\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n FeeCapTooLowError,\n type FeeCapTooLowErrorType,\n InsufficientFundsError,\n type InsufficientFundsErrorType,\n IntrinsicGasTooHighError,\n type IntrinsicGasTooHighErrorType,\n IntrinsicGasTooLowError,\n type IntrinsicGasTooLowErrorType,\n NonceMaxValueError,\n type NonceMaxValueErrorType,\n NonceTooHighError,\n type NonceTooHighErrorType,\n NonceTooLowError,\n type NonceTooLowErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n TransactionTypeNotSupportedError,\n type TransactionTypeNotSupportedErrorType,\n UnknownNodeError,\n type UnknownNodeErrorType,\n} from '../../errors/node.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport {\n InvalidInputRpcError,\n TransactionRejectedRpcError,\n} from '../../errors/rpc.js'\n\nexport function containsNodeError(err: BaseError) {\n return (\n err instanceof TransactionRejectedRpcError ||\n err instanceof InvalidInputRpcError ||\n (err instanceof RpcRequestError && err.code === ExecutionRevertedError.code)\n )\n}\n\nexport type GetNodeErrorParameters = Partial>\n\nexport type GetNodeErrorReturnType =\n | ExecutionRevertedErrorType\n | FeeCapTooHighErrorType\n | FeeCapTooLowErrorType\n | NonceTooHighErrorType\n | NonceTooLowErrorType\n | NonceMaxValueErrorType\n | InsufficientFundsErrorType\n | IntrinsicGasTooHighErrorType\n | IntrinsicGasTooLowErrorType\n | TransactionTypeNotSupportedErrorType\n | TipAboveFeeCapErrorType\n | UnknownNodeErrorType\n\nexport function getNodeError(\n err: BaseError,\n args: GetNodeErrorParameters,\n): GetNodeErrorReturnType {\n const message = (err.details || '').toLowerCase()\n\n const executionRevertedError = err.walk(\n (e) => (e as { code: number }).code === ExecutionRevertedError.code,\n )\n if (executionRevertedError instanceof BaseError) {\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\n }\n if (ExecutionRevertedError.nodeMessage.test(message))\n return new ExecutionRevertedError({\n cause: err,\n message: err.details,\n }) as any\n if (FeeCapTooHighError.nodeMessage.test(message))\n return new FeeCapTooHighError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n }) as any\n if (FeeCapTooLowError.nodeMessage.test(message))\n return new FeeCapTooLowError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n }) as any\n if (NonceTooHighError.nodeMessage.test(message))\n return new NonceTooHighError({ cause: err, nonce: args?.nonce }) as any\n if (NonceTooLowError.nodeMessage.test(message))\n return new NonceTooLowError({ cause: err, nonce: args?.nonce }) as any\n if (NonceMaxValueError.nodeMessage.test(message))\n return new NonceMaxValueError({ cause: err, nonce: args?.nonce }) as any\n if (InsufficientFundsError.nodeMessage.test(message))\n return new InsufficientFundsError({ cause: err }) as any\n if (IntrinsicGasTooHighError.nodeMessage.test(message))\n return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }) as any\n if (IntrinsicGasTooLowError.nodeMessage.test(message))\n return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }) as any\n if (TransactionTypeNotSupportedError.nodeMessage.test(message))\n return new TransactionTypeNotSupportedError({ cause: err }) as any\n if (TipAboveFeeCapError.nodeMessage.test(message))\n return new TipAboveFeeCapError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n maxPriorityFeePerGas: args?.maxPriorityFeePerGas,\n }) as any\n return new UnknownNodeError({\n cause: err,\n }) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ChainFormatter } from '../../types/chain.js'\n\nexport type ExtractErrorType = ErrorType\n\n/**\n * @description Picks out the keys from `value` that exist in the formatter..\n */\nexport function extract(\n value_: Record,\n { format }: { format?: ChainFormatter['format'] },\n) {\n if (!format) return {}\n\n const value: Record = {}\n function extract_(formatted: Record) {\n const keys = Object.keys(formatted)\n for (const key of keys) {\n if (key in value_) value[key] = value_[key]\n if (\n formatted[key] &&\n typeof formatted[key] === 'object' &&\n !Array.isArray(formatted[key])\n )\n extract_(formatted[key])\n }\n }\n\n const formatted = format(value_ || {})\n extract_(formatted)\n\n return value\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport { numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n TChain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n TChain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n transactionRequest: Partial,\n) {\n return {\n ...transactionRequest,\n gas:\n typeof transactionRequest.gas !== 'undefined'\n ? numberToHex(transactionRequest.gas)\n : undefined,\n gasPrice:\n typeof transactionRequest.gasPrice !== 'undefined'\n ? numberToHex(transactionRequest.gasPrice)\n : undefined,\n maxFeePerGas:\n typeof transactionRequest.maxFeePerGas !== 'undefined'\n ? numberToHex(transactionRequest.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas:\n typeof transactionRequest.maxPriorityFeePerGas !== 'undefined'\n ? numberToHex(transactionRequest.maxPriorityFeePerGas)\n : undefined,\n nonce:\n typeof transactionRequest.nonce !== 'undefined'\n ? numberToHex(transactionRequest.nonce)\n : undefined,\n type:\n typeof transactionRequest.type !== 'undefined'\n ? rpcTransactionType[transactionRequest.type]\n : undefined,\n value:\n typeof transactionRequest.value !== 'undefined'\n ? numberToHex(transactionRequest.value)\n : undefined,\n } as RpcTransactionRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n","import type { AbiEvent } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { getEventSignature } from './getEventSignature.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type GetEventSelectorErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport const getEventSelector = (fn: string | AbiEvent) =>\n hash(getEventSignature(fn))\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type GetFunctionSignatureErrorType,\n getFunctionSignature,\n} from './getFunctionSignature.js'\n\nexport type GetEventSignatureErrorType =\n | GetFunctionSignatureErrorType\n | ErrorType\n\nexport const getEventSignature = (fn: string | AbiEvent) => {\n return getFunctionSignature(fn as {} as AbiFunction)\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport {\n type GetFunctionSignatureErrorType,\n getFunctionSignature,\n} from './getFunctionSignature.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type GetFunctionSelectorErrorType =\n | GetFunctionSignatureErrorType\n | Keccak256ErrorType\n | SliceErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport const getFunctionSelector = (fn: string | AbiFunction) =>\n slice(hash(getFunctionSignature(fn)), 0, 4)\n","// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.\n// https://twitter.com/GabrielVergnaud/status/1622906834343366657\nexport function execTyped(regex: RegExp, string: string) {\n const match = regex.exec(string)\n return match?.groups as T | undefined\n}\n\n// `bytes`: binary type of `M` bytes, `0 < M <= 32`\n// https://regexr.com/6va55\nexport const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/\n\n// `(u)int`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex =\n /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/\n\nexport const isTupleRegex = /^\\(.+?\\).*?$/\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport { execTyped } from '../regex.js'\nimport type { IsNarrowable, Join } from '../types.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param TAbiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * type Result = FormatAbiParameter<{ type: 'address'; name: 'from'; }>\n * // ^? type Result = 'address from'\n */\nexport type FormatAbiParameter<\n TAbiParameter extends AbiParameter | AbiEventParameter,\n> = TAbiParameter extends {\n name?: infer Name extends string\n type: `tuple${infer Array}`\n components: infer Components extends readonly AbiParameter[]\n indexed?: infer Indexed extends boolean\n}\n ? FormatAbiParameter<\n {\n type: `(${Join<\n {\n [K in keyof Components]: FormatAbiParameter<\n {\n type: Components[K]['type']\n } & (IsNarrowable extends true\n ? { name: Components[K]['name'] }\n : unknown) &\n (Components[K] extends { components: readonly AbiParameter[] }\n ? { components: Components[K]['components'] }\n : unknown)\n >\n },\n ', '\n >})${Array}`\n } & (IsNarrowable extends true ? { name: Name } : unknown) &\n (IsNarrowable extends true\n ? { indexed: Indexed }\n : unknown)\n >\n : `${TAbiParameter['type']}${TAbiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${TAbiParameter['name'] extends infer Name extends string\n ? Name extends ''\n ? ''\n : ` ${AssertName}`\n : ''}`\n\n// https://regexr.com/7f7rv\nconst tupleRegex = /^tuple(?(\\[(\\d*)\\])*)$/\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param abiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * const result = formatAbiParameter({ type: 'address', name: 'from' })\n * // ^? const result: 'address from'\n */\nexport function formatAbiParameter<\n const TAbiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: TAbiParameter): FormatAbiParameter {\n type Result = FormatAbiParameter\n\n let type = abiParameter.type\n if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {\n type = '('\n const length = abiParameter.components.length as number\n for (let i = 0; i < length; i++) {\n const component = abiParameter.components[i]!\n type += formatAbiParameter(component)\n if (i < length - 1) type += ', '\n }\n const result = execTyped<{ array?: string }>(tupleRegex, abiParameter.type)\n type += `)${result?.array ?? ''}`\n return formatAbiParameter({\n ...abiParameter,\n type,\n }) as Result\n }\n // Add `indexed` to type if in `abiParameter`\n if ('indexed' in abiParameter && abiParameter.indexed)\n type = `${type} indexed`\n // Return human-readable ABI parameter\n if (abiParameter.name) return `${type} ${abiParameter.name}` as Result\n return type as Result\n}\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport type { Join } from '../types.js'\nimport {\n type FormatAbiParameter,\n formatAbiParameter,\n} from './formatAbiParameter.js'\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameter.\n *\n * @param TAbiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * type Result = FormatAbiParameters<[\n * // ^? type Result = 'address from, uint256 tokenId'\n * { type: 'address'; name: 'from'; },\n * { type: 'uint256'; name: 'tokenId'; },\n * ]>\n */\nexport type FormatAbiParameters<\n TAbiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [K in keyof TAbiParameters]: FormatAbiParameter\n },\n ', '\n>\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameters.\n *\n * @param abiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * const result = formatAbiParameters([\n * // ^? const result: 'address from, uint256 tokenId'\n * { type: 'address', name: 'from' },\n * { type: 'uint256', name: 'tokenId' },\n * ])\n */\nexport function formatAbiParameters<\n const TAbiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: TAbiParameters): FormatAbiParameters {\n let params = ''\n const length = abiParameters.length\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i]!\n params += formatAbiParameter(abiParameter)\n if (i !== length - 1) params += ', '\n }\n return params as FormatAbiParameters\n}\n","import { type AbiFunction, formatAbiItem } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type NormalizeSignatureErrorType,\n normalizeSignature,\n} from './normalizeSignature.js'\n\nexport type GetFunctionSignatureErrorType =\n | NormalizeSignatureErrorType\n | ErrorType\n\nexport const getFunctionSignature = (fn_: string | AbiFunction) => {\n const fn = (() => {\n if (typeof fn_ === 'string') return fn_\n return formatAbiItem(fn_)\n })()\n return normalizeSignature(fn)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nexport type NormalizeSignatureParameters = string\nexport type NormalizeSignatureReturnType = string\nexport type NormalizeSignatureErrorType = ErrorType\n\nexport function normalizeSignature(\n signature: NormalizeSignatureParameters,\n): NormalizeSignatureReturnType {\n let active = true\n let current = ''\n let level = 0\n let result = ''\n let valid = false\n\n for (let i = 0; i < signature.length; i++) {\n const char = signature[i]\n\n // If the character is a separator, we want to reactivate.\n if (['(', ')', ','].includes(char)) active = true\n\n // If the character is a \"level\" token, we want to increment/decrement.\n if (char === '(') level++\n if (char === ')') level--\n\n // If we aren't active, we don't want to mutate the result.\n if (!active) continue\n\n // If level === 0, we are at the definition level.\n if (level === 0) {\n if (char === ' ' && ['event', 'function', ''].includes(result))\n result = ''\n else {\n result += char\n\n // If we are at the end of the definition, we must be finished.\n if (char === ')') {\n valid = true\n break\n }\n }\n\n continue\n }\n\n // Ignore spaces\n if (char === ' ') {\n // If the previous character is a separator, and the current section isn't empty, we want to deactivate.\n if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {\n current = ''\n active = false\n }\n continue\n }\n\n result += char\n current += char\n }\n\n if (!valid) throw new BaseError('Unable to normalize signature.')\n\n return result\n}\n","import type {\n Abi,\n AbiConstructor,\n AbiError,\n AbiEvent,\n AbiEventParameter,\n AbiFallback,\n AbiFunction,\n AbiParameter,\n AbiReceive,\n AbiStateMutability,\n} from '../abi.js'\nimport {\n type FormatAbiParameters as FormatAbiParameters_,\n formatAbiParameters,\n} from './formatAbiParameters.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param TAbiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem =\n Abi[number] extends TAbiItem\n ? string\n :\n | (TAbiItem extends AbiFunction\n ? AbiFunction extends TAbiItem\n ? string\n : `function ${AssertName}(${FormatAbiParameters<\n TAbiItem['inputs']\n >})${TAbiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${TAbiItem['stateMutability']}`\n : ''}${TAbiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters})`}`\n : never)\n | (TAbiItem extends AbiEvent\n ? AbiEvent extends TAbiItem\n ? string\n : `event ${AssertName}(${FormatAbiParameters<\n TAbiItem['inputs']\n >})`\n : never)\n | (TAbiItem extends AbiError\n ? AbiError extends TAbiItem\n ? string\n : `error ${AssertName}(${FormatAbiParameters<\n TAbiItem['inputs']\n >})`\n : never)\n | (TAbiItem extends AbiConstructor\n ? AbiConstructor extends TAbiItem\n ? string\n : `constructor(${FormatAbiParameters<\n TAbiItem['inputs']\n >})${TAbiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (TAbiItem extends AbiFallback\n ? AbiFallback extends TAbiItem\n ? string\n : 'fallback()'\n : never)\n | (TAbiItem extends AbiReceive\n ? AbiReceive extends TAbiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n TAbiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = TAbiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n TAbiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? TAbiParameters\n : never\n >\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport function formatAbiItem(\n abiItem: TAbiItem,\n): FormatAbiItem {\n type Result = FormatAbiItem\n type Params = readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n\n if (abiItem.type === 'function')\n return `function ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})${\n abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'\n ? ` ${abiItem.stateMutability}`\n : ''\n }${\n abiItem.outputs.length\n ? ` returns (${formatAbiParameters(abiItem.outputs as Params)})`\n : ''\n }`\n else if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n else if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n else if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n else if (abiItem.type === 'fallback') return 'fallback()' as Result\n return 'receive() external payable' as Result\n}\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport {\n Hash,\n u32,\n Input,\n toBytes,\n wrapConstructor,\n wrapXOFConstructorWithOpts,\n HashXOF,\n} from './utils.js';\n\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s: Uint32Array, rounds: number = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++) B[x] = s[y + x];\n for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\n\nexport class Keccak extends Hash implements HashXOF {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n public blockLen: number,\n public suffix: number,\n public outputLen: number,\n protected enableXOF = false,\n protected rounds: number = 24\n ) {\n super();\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n protected keccak() {\n keccakP(this.state32, this.rounds);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish() {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: Uint8Array): Uint8Array {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array) {\n output(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\n\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n wrapXOFConstructorWithOpts, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n","import { keccak_256 } from '@noble/hashes/sha3'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Keccak256Hash =\n | (TTo extends 'bytes' ? ByteArray : never)\n | (TTo extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function keccak256(\n value: Hex | ByteArray,\n to_?: TTo,\n): Keccak256Hash {\n const to = to_ || 'hex'\n const bytes = keccak_256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Keccak256Hash\n return toHex(bytes) as Keccak256Hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\ntype Resolved = [\n result: TReturnType[number],\n results: TReturnType,\n]\n\ntype PendingPromise = {\n resolve?: (data: Resolved) => void\n reject?: (reason?: unknown) => void\n}\n\ntype SchedulerItem = { args: unknown; pendingPromise: PendingPromise }\n\ntype BatchResultsCompareFn = (\n a: TResult,\n b: TResult,\n) => number\n\nexport type CreateBatchSchedulerArguments<\n TParameters = unknown,\n TReturnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: TParameters[]) => Promise\n id: number | string\n shouldSplitBatch?: (args: TParameters[]) => boolean\n wait?: number\n sort?: BatchResultsCompareFn\n}\n\nexport type CreateBatchSchedulerReturnType<\n TParameters = unknown,\n TReturnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: TParameters extends undefined\n ? (args?: TParameters) => Promise>\n : (args: TParameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\nexport function createBatchScheduler<\n TParameters,\n TReturnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n TParameters,\n TReturnType\n>): CreateBatchSchedulerReturnType {\n const exec = async () => {\n const scheduler = getScheduler()\n flush()\n\n const args = scheduler.map(({ args }) => args)\n\n if (args.length === 0) return\n\n fn(args as TParameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { pendingPromise } = scheduler[i]\n pendingPromise.resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { pendingPromise } = scheduler[i]\n pendingPromise.reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as TParameters[]\n\n const getScheduler = () => schedulerCache.get(id) || []\n\n const setScheduler = (item: SchedulerItem) =>\n schedulerCache.set(id, [...getScheduler(), item])\n\n return {\n flush,\n async schedule(args: TParameters) {\n const pendingPromise: PendingPromise = {}\n const promise = new Promise>((resolve, reject) => {\n pendingPromise.resolve = resolve\n pendingPromise.reject = reject\n })\n\n const split = shouldSplitBatch?.([...getBatchedArgs(), args])\n\n if (split) exec()\n\n const hasActiveScheduler = getScheduler().length > 0\n if (hasActiveScheduler) {\n setScheduler({ args, pendingPromise })\n return promise\n }\n\n setScheduler({ args, pendingPromise })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","import type { ErrorType } from '../errors/utils.js'\n\nexport type StringifyErrorType = ErrorType\n\nexport const stringify: typeof JSON.stringify = (value, replacer, space) =>\n JSON.stringify(\n value,\n (key, value_) => {\n const value = typeof value_ === 'bigint' ? value_.toString() : value_\n return typeof replacer === 'function' ? replacer(key, value) : value\n },\n space,\n )\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport {\n FeeConflictError,\n type FeeConflictErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = Partial>\n\nexport type AssertRequestErrorType =\n | InvalidAddressErrorType\n | FeeConflictErrorType\n | FeeCapTooHighErrorType\n | ParseAccountErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertRequest(args: AssertRequestParameters) {\n const {\n account: account_,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n if (account && !isAddress(account.address))\n throw new InvalidAddressError({ address: account.address })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (\n typeof gasPrice !== 'undefined' &&\n (typeof maxFeePerGas !== 'undefined' ||\n typeof maxPriorityFeePerGas !== 'undefined')\n )\n throw new FeeConflictError()\n\n if (maxFeePerGas && maxFeePerGas > 2n ** 256n - 1n)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import { etherUnits } from '../../constants/unit.js'\n\nimport { type FormatUnitsErrorType, formatUnits } from './formatUnits.js'\n\nexport type FormatEtherErrorType = FormatUnitsErrorType\n\n/**\n * Converts numerical wei to a string representation of ether.\n *\n * - Docs: https://viem.sh/docs/utilities/formatEther.html\n *\n * @example\n * import { formatEther } from 'viem'\n *\n * formatEther(1000000000000000000n)\n * // '1'\n */\nexport function formatEther(wei: bigint, unit: 'wei' | 'gwei' = 'wei') {\n return formatUnits(wei, etherUnits[unit])\n}\n","import { gweiUnits } from '../../constants/unit.js'\n\nimport { type FormatUnitsErrorType, formatUnits } from './formatUnits.js'\n\nexport type FormatGweiErrorType = FormatUnitsErrorType\n\n/**\n * Converts numerical wei to a string representation of gwei.\n *\n * - Docs: https://viem.sh/docs/utilities/formatGwei.html\n *\n * @example\n * import { formatGwei } from 'viem'\n *\n * formatGwei(1000000000n)\n * // '1'\n */\nexport function formatGwei(wei: bigint, unit: 'wei' = 'wei') {\n return formatUnits(wei, gweiUnits[unit])\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type FormatUnitsErrorType = ErrorType\n\n/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number..\n *\n * - Docs: https://viem.sh/docs/utilities/formatUnits.html\n *\n * @example\n * import { formatUnits } from 'viem'\n *\n * formatUnits(420000000000n, 9)\n * // '420'\n */\nexport function formatUnits(value: bigint, decimals: number) {\n let display = value.toString()\n\n const negative = display.startsWith('-')\n if (negative) display = display.slice(1)\n\n display = display.padStart(decimals, '0')\n\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ]\n fraction = fraction.replace(/(0+)$/, '')\n return `${negative ? '-' : ''}${integer || '0'}${\n fraction ? `.${fraction}` : ''\n }`\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"static/js/\" + chunkId + \".\" + {\"54\":\"bc619b11\",\"458\":\"6a8a7d24\",\"774\":\"d2e729fe\",\"807\":\"86b329b6\",\"820\":\"f0ee2f14\",\"858\":\"c5d0b516\",\"910\":\"131ad245\"}[chunkId] + \".chunk.js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","var inProgress = {};\nvar dataWebpackPrefix = \"tomopool-app:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunktomopool_app\"] = self[\"webpackChunktomopool_app\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","__webpack_require__.nc = undefined;","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n 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;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","export var MS = '-ms-'\nexport var MOZ = '-moz-'\nexport var WEBKIT = '-webkit-'\n\nexport var COMMENT = 'comm'\nexport var RULESET = 'rule'\nexport var DECLARATION = 'decl'\n\nexport var PAGE = '@page'\nexport var MEDIA = '@media'\nexport var IMPORT = '@import'\nexport var CHARSET = '@charset'\nexport var VIEWPORT = '@viewport'\nexport var SUPPORTS = '@supports'\nexport var DOCUMENT = '@document'\nexport var NAMESPACE = '@namespace'\nexport var KEYFRAMES = '@keyframes'\nexport var FONT_FACE = '@font-face'\nexport var COUNTER_STYLE = '@counter-style'\nexport var FONT_FEATURE_VALUES = '@font-feature-values'\nexport var LAYER = '@layer'\n","/**\n * @param {number}\n * @return {number}\n */\nexport var abs = Math.abs\n\n/**\n * @param {number}\n * @return {string}\n */\nexport var from = String.fromCharCode\n\n/**\n * @param {object}\n * @return {object}\n */\nexport var assign = Object.assign\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {number}\n */\nexport function hash (value, length) {\n\treturn charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0\n}\n\n/**\n * @param {string} value\n * @return {string}\n */\nexport function trim (value) {\n\treturn value.trim()\n}\n\n/**\n * @param {string} value\n * @param {RegExp} pattern\n * @return {string?}\n */\nexport function match (value, pattern) {\n\treturn (value = pattern.exec(value)) ? value[0] : value\n}\n\n/**\n * @param {string} value\n * @param {(string|RegExp)} pattern\n * @param {string} replacement\n * @return {string}\n */\nexport function replace (value, pattern, replacement) {\n\treturn value.replace(pattern, replacement)\n}\n\n/**\n * @param {string} value\n * @param {string} search\n * @return {number}\n */\nexport function indexof (value, search) {\n\treturn value.indexOf(search)\n}\n\n/**\n * @param {string} value\n * @param {number} index\n * @return {number}\n */\nexport function charat (value, index) {\n\treturn value.charCodeAt(index) | 0\n}\n\n/**\n * @param {string} value\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function substr (value, begin, end) {\n\treturn value.slice(begin, end)\n}\n\n/**\n * @param {string} value\n * @return {number}\n */\nexport function strlen (value) {\n\treturn value.length\n}\n\n/**\n * @param {any[]} value\n * @return {number}\n */\nexport function sizeof (value) {\n\treturn value.length\n}\n\n/**\n * @param {any} value\n * @param {any[]} array\n * @return {any}\n */\nexport function append (value, array) {\n\treturn array.push(value), value\n}\n\n/**\n * @param {string[]} array\n * @param {function} callback\n * @return {string}\n */\nexport function combine (array, callback) {\n\treturn array.map(callback).join('')\n}\n\n/**\n * @param {string[]} array\n * @param {RegExp} pattern\n * @return {string[]}\n */\nexport function filter (array, pattern) {\n\treturn array.filter(function (value) { return !match(value, pattern) })\n}\n","import {from, trim, charat, strlen, substr, append, assign} from './Utility.js'\n\nexport var line = 1\nexport var column = 1\nexport var length = 0\nexport var position = 0\nexport var character = 0\nexport var characters = ''\n\n/**\n * @param {string} value\n * @param {object | null} root\n * @param {object | null} parent\n * @param {string} type\n * @param {string[] | string} props\n * @param {object[] | string} children\n * @param {object[]} siblings\n * @param {number} length\n */\nexport function node (value, root, parent, type, props, children, length, siblings) {\n\treturn {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: '', siblings: siblings}\n}\n\n/**\n * @param {object} root\n * @param {object} props\n * @return {object}\n */\nexport function copy (root, props) {\n\treturn assign(node('', null, null, '', null, null, 0, root.siblings), root, {length: -root.length}, props)\n}\n\n/**\n * @param {object} root\n */\nexport function lift (root) {\n\twhile (root.root)\n\t\troot = copy(root.root, {children: [root]})\n\n\tappend(root, root.siblings)\n}\n\n/**\n * @return {number}\n */\nexport function char () {\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function prev () {\n\tcharacter = position > 0 ? charat(characters, --position) : 0\n\n\tif (column--, character === 10)\n\t\tcolumn = 1, line--\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function next () {\n\tcharacter = position < length ? charat(characters, position++) : 0\n\n\tif (column++, character === 10)\n\t\tcolumn = 1, line++\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function peek () {\n\treturn charat(characters, position)\n}\n\n/**\n * @return {number}\n */\nexport function caret () {\n\treturn position\n}\n\n/**\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function slice (begin, end) {\n\treturn substr(characters, begin, end)\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function token (type) {\n\tswitch (type) {\n\t\t// \\0 \\t \\n \\r \\s whitespace token\n\t\tcase 0: case 9: case 10: case 13: case 32:\n\t\t\treturn 5\n\t\t// ! + , / > @ ~ isolate token\n\t\tcase 33: case 43: case 44: case 47: case 62: case 64: case 126:\n\t\t// ; { } breakpoint token\n\t\tcase 59: case 123: case 125:\n\t\t\treturn 4\n\t\t// : accompanied token\n\t\tcase 58:\n\t\t\treturn 3\n\t\t// \" ' ( [ opening delimit token\n\t\tcase 34: case 39: case 40: case 91:\n\t\t\treturn 2\n\t\t// ) ] closing delimit token\n\t\tcase 41: case 93:\n\t\t\treturn 1\n\t}\n\n\treturn 0\n}\n\n/**\n * @param {string} value\n * @return {any[]}\n */\nexport function alloc (value) {\n\treturn line = column = 1, length = strlen(characters = value), position = 0, []\n}\n\n/**\n * @param {any} value\n * @return {any}\n */\nexport function dealloc (value) {\n\treturn characters = '', value\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function delimit (type) {\n\treturn trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))\n}\n\n/**\n * @param {string} value\n * @return {string[]}\n */\nexport function tokenize (value) {\n\treturn dealloc(tokenizer(alloc(value)))\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function whitespace (type) {\n\twhile (character = peek())\n\t\tif (character < 33)\n\t\t\tnext()\n\t\telse\n\t\t\tbreak\n\n\treturn token(type) > 2 || token(character) > 3 ? '' : ' '\n}\n\n/**\n * @param {string[]} children\n * @return {string[]}\n */\nexport function tokenizer (children) {\n\twhile (next())\n\t\tswitch (token(character)) {\n\t\t\tcase 0: append(identifier(position - 1), children)\n\t\t\t\tbreak\n\t\t\tcase 2: append(delimit(character), children)\n\t\t\t\tbreak\n\t\t\tdefault: append(from(character), children)\n\t\t}\n\n\treturn children\n}\n\n/**\n * @param {number} index\n * @param {number} count\n * @return {string}\n */\nexport function escaping (index, count) {\n\twhile (--count && next())\n\t\t// not 0-9 A-F a-f\n\t\tif (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))\n\t\t\tbreak\n\n\treturn slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function delimiter (type) {\n\twhile (next())\n\t\tswitch (character) {\n\t\t\t// ] ) \" '\n\t\t\tcase type:\n\t\t\t\treturn position\n\t\t\t// \" '\n\t\t\tcase 34: case 39:\n\t\t\t\tif (type !== 34 && type !== 39)\n\t\t\t\t\tdelimiter(character)\n\t\t\t\tbreak\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (type === 41)\n\t\t\t\t\tdelimiter(type)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tnext()\n\t\t\t\tbreak\n\t\t}\n\n\treturn position\n}\n\n/**\n * @param {number} type\n * @param {number} index\n * @return {number}\n */\nexport function commenter (type, index) {\n\twhile (next())\n\t\t// //\n\t\tif (type + character === 47 + 10)\n\t\t\tbreak\n\t\t// /*\n\t\telse if (type + character === 42 + 42 && peek() === 47)\n\t\t\tbreak\n\n\treturn '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next())\n}\n\n/**\n * @param {number} index\n * @return {string}\n */\nexport function identifier (index) {\n\twhile (!token(peek()))\n\t\tnext()\n\n\treturn slice(index, position)\n}\n","import {IMPORT, LAYER, COMMENT, RULESET, DECLARATION, KEYFRAMES} from './Enum.js'\nimport {strlen} from './Utility.js'\n\n/**\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function serialize (children, callback) {\n\tvar output = ''\n\n\tfor (var i = 0; i < children.length; i++)\n\t\toutput += callback(children[i], i, children, callback) || ''\n\n\treturn output\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function stringify (element, index, children, callback) {\n\tswitch (element.type) {\n\t\tcase LAYER: if (element.children.length) break\n\t\tcase IMPORT: case DECLARATION: return element.return = element.return || element.value\n\t\tcase COMMENT: return ''\n\t\tcase KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'\n\t\tcase RULESET: if (!strlen(element.value = element.props.join(','))) return ''\n\t}\n\n\treturn strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''\n}\n","import {MS, MOZ, WEBKIT} from './Enum.js'\nimport {hash, charat, strlen, indexof, replace, substr, match} from './Utility.js'\n\n/**\n * @param {string} value\n * @param {number} length\n * @param {object[]} children\n * @return {string}\n */\nexport function prefix (value, length, children) {\n\tswitch (hash(value, length)) {\n\t\t// color-adjust\n\t\tcase 5103:\n\t\t\treturn WEBKIT + 'print-' + value + value\n\t\t// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)\n\t\tcase 5737: case 4201: case 3177: case 3433: case 1641: case 4457: case 2921:\n\t\t// text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break\n\t\tcase 5572: case 6356: case 5844: case 3191: case 6645: case 3005:\n\t\t// mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,\n\t\tcase 6391: case 5879: case 5623: case 6135: case 4599: case 4855:\n\t\t// background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)\n\t\tcase 4215: case 6389: case 5109: case 5365: case 5621: case 3829:\n\t\t\treturn WEBKIT + value + value\n\t\t// tab-size\n\t\tcase 4789:\n\t\t\treturn MOZ + value + value\n\t\t// appearance, user-select, transform, hyphens, text-size-adjust\n\t\tcase 5349: case 4246: case 4810: case 6968: case 2756:\n\t\t\treturn WEBKIT + value + MOZ + value + MS + value + value\n\t\t// writing-mode\n\t\tcase 5936:\n\t\t\tswitch (charat(value, length + 11)) {\n\t\t\t\t// vertical-l(r)\n\t\t\t\tcase 114:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb') + value\n\t\t\t\t// vertical-r(l)\n\t\t\t\tcase 108:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb-rl') + value\n\t\t\t\t// horizontal(-)tb\n\t\t\t\tcase 45:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'lr') + value\n\t\t\t\t// default: fallthrough to below\n\t\t\t}\n\t\t// flex, flex-direction, scroll-snap-type, writing-mode\n\t\tcase 6828: case 4268: case 2903:\n\t\t\treturn WEBKIT + value + MS + value + value\n\t\t// order\n\t\tcase 6165:\n\t\t\treturn WEBKIT + value + MS + 'flex-' + value + value\n\t\t// align-items\n\t\tcase 5187:\n\t\t\treturn WEBKIT + value + replace(value, /(\\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value\n\t\t// align-self\n\t\tcase 5443:\n\t\t\treturn WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/g, '') + (!match(value, /flex-|baseline/) ? MS + 'grid-row-' + replace(value, /flex-|-self/g, '') : '') + value\n\t\t// align-content\n\t\tcase 4675:\n\t\t\treturn WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/g, '') + value\n\t\t// flex-shrink\n\t\tcase 5548:\n\t\t\treturn WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value\n\t\t// flex-basis\n\t\tcase 5292:\n\t\t\treturn WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value\n\t\t// flex-grow\n\t\tcase 6060:\n\t\t\treturn WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value\n\t\t// transition\n\t\tcase 4554:\n\t\t\treturn WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value\n\t\t// cursor\n\t\tcase 6187:\n\t\t\treturn replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value\n\t\t// background, background-image\n\t\tcase 5495: case 3959:\n\t\t\treturn replace(value, /(image-set\\([^]*)/, WEBKIT + '$1' + '$`$1')\n\t\t// justify-content\n\t\tcase 4968:\n\t\t\treturn replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value\n\t\t// justify-self\n\t\tcase 4200:\n\t\t\tif (!match(value, /flex-|baseline/)) return MS + 'grid-column-align' + substr(value, length) + value\n\t\t\tbreak\n\t\t// grid-template-(columns|rows)\n\t\tcase 2592: case 3360:\n\t\t\treturn MS + replace(value, 'template-', '') + value\n\t\t// grid-(row|column)-start\n\t\tcase 4384: case 3616:\n\t\t\tif (children && children.some(function (element, index) { return length = index, match(element.props, /grid-\\w+-end/) })) {\n\t\t\t\treturn ~indexof(value + (children = children[length].value), 'span') ? value : (MS + replace(value, '-start', '') + value + MS + 'grid-row-span:' + (~indexof(children, 'span') ? match(children, /\\d+/) : +match(children, /\\d+/) - +match(value, /\\d+/)) + ';')\n\t\t\t}\n\t\t\treturn MS + replace(value, '-start', '') + value\n\t\t// grid-(row|column)-end\n\t\tcase 4896: case 4128:\n\t\t\treturn (children && children.some(function (element) { return match(element.props, /grid-\\w+-start/) })) ? value : MS + replace(replace(value, '-end', '-span'), 'span ', '') + value\n\t\t// (margin|padding)-inline-(start|end)\n\t\tcase 4095: case 3583: case 4068: case 2532:\n\t\t\treturn replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value\n\t\t// (min|max)?(width|height|inline-size|block-size)\n\t\tcase 8116: case 7059: case 5753: case 5535:\n\t\tcase 5445: case 5701: case 4933: case 4677:\n\t\tcase 5533: case 5789: case 5021: case 4765:\n\t\t\t// stretch, max-content, min-content, fill-available\n\t\t\tif (strlen(value) - 1 - length > 6)\n\t\t\t\tswitch (charat(value, length + 1)) {\n\t\t\t\t\t// (m)ax-content, (m)in-content\n\t\t\t\t\tcase 109:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (charat(value, length + 4) !== 45)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t// (f)ill-available, (f)it-content\n\t\t\t\t\tcase 102:\n\t\t\t\t\t\treturn replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value\n\t\t\t\t\t// (s)tretch\n\t\t\t\t\tcase 115:\n\t\t\t\t\t\treturn ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length, children) + value : value\n\t\t\t\t}\n\t\t\tbreak\n\t\t// grid-(column|row)\n\t\tcase 5152: case 5920:\n\t\t\treturn replace(value, /(.+?):(\\d+)(\\s*\\/\\s*(span)?\\s*(\\d+))?(.*)/, function (_, a, b, c, d, e, f) { return (MS + a + ':' + b + f) + (c ? (MS + a + '-span:' + (d ? e : +e - +b)) + f : '') + value })\n\t\t// position: sticky\n\t\tcase 4949:\n\t\t\t// stick(y)?\n\t\t\tif (charat(value, length + 6) === 121)\n\t\t\t\treturn replace(value, ':', ':' + WEBKIT) + value\n\t\t\tbreak\n\t\t// display: (flex|inline-flex|grid|inline-grid)\n\t\tcase 6444:\n\t\t\tswitch (charat(value, charat(value, 14) === 45 ? 18 : 11)) {\n\t\t\t\t// (inline-)?fle(x)\n\t\t\t\tcase 120:\n\t\t\t\t\treturn replace(value, /(.+:)([^;\\s!]+)(;|(\\s+)?!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value\n\t\t\t\t// (inline-)?gri(d)\n\t\t\t\tcase 100:\n\t\t\t\t\treturn replace(value, ':', ':' + MS) + value\n\t\t\t}\n\t\t\tbreak\n\t\t// scroll-margin, scroll-margin-(top|right|bottom|left)\n\t\tcase 5719: case 2647: case 2135: case 3927: case 2391:\n\t\t\treturn replace(value, 'scroll-', 'scroll-snap-') + value\n\t}\n\n\treturn value\n}\n","import {MS, MOZ, WEBKIT, RULESET, KEYFRAMES, DECLARATION} from './Enum.js'\nimport {match, charat, substr, strlen, sizeof, replace, combine, filter, assign} from './Utility.js'\nimport {copy, lift, tokenize} from './Tokenizer.js'\nimport {serialize} from './Serializer.js'\nimport {prefix} from './Prefixer.js'\n\n/**\n * @param {function[]} collection\n * @return {function}\n */\nexport function middleware (collection) {\n\tvar length = sizeof(collection)\n\n\treturn function (element, index, children, callback) {\n\t\tvar output = ''\n\n\t\tfor (var i = 0; i < length; i++)\n\t\t\toutput += collection[i](element, index, children, callback) || ''\n\n\t\treturn output\n\t}\n}\n\n/**\n * @param {function} callback\n * @return {function}\n */\nexport function rulesheet (callback) {\n\treturn function (element) {\n\t\tif (!element.root)\n\t\t\tif (element = element.return)\n\t\t\t\tcallback(element)\n\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n */\nexport function prefixer (element, index, children, callback) {\n\tif (element.length > -1)\n\t\tif (!element.return)\n\t\t\tswitch (element.type) {\n\t\t\t\tcase DECLARATION: element.return = prefix(element.value, element.length, children)\n\t\t\t\t\treturn\n\t\t\t\tcase KEYFRAMES:\n\t\t\t\t\treturn serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)\n\t\t\t\tcase RULESET:\n\t\t\t\t\tif (element.length)\n\t\t\t\t\t\treturn combine(children = element.props, function (value) {\n\t\t\t\t\t\t\tswitch (match(value, callback = /(::plac\\w+|:read-\\w+)/)) {\n\t\t\t\t\t\t\t\t// :read-(only|write)\n\t\t\t\t\t\t\t\tcase ':read-only': case ':read-write':\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [replace(value, /:(read-\\w+)/, ':' + MOZ + '$1')]}))\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [value]}))\n\t\t\t\t\t\t\t\t\tassign(element, {props: filter(children, callback)})\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t// :placeholder\n\t\t\t\t\t\t\t\tcase '::placeholder':\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [replace(value, /:(plac\\w+)/, ':' + WEBKIT + 'input-$1')]}))\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [replace(value, /:(plac\\w+)/, ':' + MOZ + '$1')]}))\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [replace(value, /:(plac\\w+)/, MS + 'input-$1')]}))\n\t\t\t\t\t\t\t\t\tlift(copy(element, {props: [value]}))\n\t\t\t\t\t\t\t\t\tassign(element, {props: filter(children, callback)})\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn ''\n\t\t\t\t\t\t})\n\t\t\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n */\nexport function namespace (element) {\n\tswitch (element.type) {\n\t\tcase RULESET:\n\t\t\telement.props = element.props.map(function (value) {\n\t\t\t\treturn combine(tokenize(value), function (value, index, children) {\n\t\t\t\t\tswitch (charat(value, 0)) {\n\t\t\t\t\t\t// \\f\n\t\t\t\t\t\tcase 12:\n\t\t\t\t\t\t\treturn substr(value, 1, strlen(value))\n\t\t\t\t\t\t// \\0 ( + > ~\n\t\t\t\t\t\tcase 0: case 40: case 43: case 62: case 126:\n\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t// :\n\t\t\t\t\t\tcase 58:\n\t\t\t\t\t\t\tif (children[++index] === 'global')\n\t\t\t\t\t\t\t\tchildren[index] = '', children[++index] = '\\f' + substr(children[index], index = 1, -1)\n\t\t\t\t\t\t// \\s\n\t\t\t\t\t\tcase 32:\n\t\t\t\t\t\t\treturn index === 1 ? '' : value\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tswitch (index) {\n\t\t\t\t\t\t\t\tcase 0: element = value\n\t\t\t\t\t\t\t\t\treturn sizeof(children) > 1 ? '' : value\n\t\t\t\t\t\t\t\tcase index = sizeof(children) - 1: case 2:\n\t\t\t\t\t\t\t\t\treturn index === 2 ? value + element + element : value + element\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t}\n}\n","import {COMMENT, RULESET, DECLARATION} from './Enum.js'\nimport {abs, charat, trim, from, sizeof, strlen, substr, append, replace, indexof} from './Utility.js'\nimport {node, char, prev, next, peek, caret, alloc, dealloc, delimit, whitespace, escaping, identifier, commenter} from './Tokenizer.js'\n\n/**\n * @param {string} value\n * @return {object[]}\n */\nexport function compile (value) {\n\treturn dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {string[]} rule\n * @param {string[]} rules\n * @param {string[]} rulesets\n * @param {number[]} pseudo\n * @param {number[]} points\n * @param {string[]} declarations\n * @return {object}\n */\nexport function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {\n\tvar index = 0\n\tvar offset = 0\n\tvar length = pseudo\n\tvar atrule = 0\n\tvar property = 0\n\tvar previous = 0\n\tvar variable = 1\n\tvar scanning = 1\n\tvar ampersand = 1\n\tvar character = 0\n\tvar type = ''\n\tvar props = rules\n\tvar children = rulesets\n\tvar reference = rule\n\tvar characters = type\n\n\twhile (scanning)\n\t\tswitch (previous = character, character = next()) {\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (previous != 108 && charat(characters, length - 1) == 58) {\n\t\t\t\t\tif (indexof(characters += replace(delimit(character), '&', '&\\f'), '&\\f') != -1)\n\t\t\t\t\t\tampersand = -1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t// \" ' [\n\t\t\tcase 34: case 39: case 91:\n\t\t\t\tcharacters += delimit(character)\n\t\t\t\tbreak\n\t\t\t// \\t \\n \\r \\s\n\t\t\tcase 9: case 10: case 13: case 32:\n\t\t\t\tcharacters += whitespace(previous)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tcharacters += escaping(caret() - 1, 7)\n\t\t\t\tcontinue\n\t\t\t// /\n\t\t\tcase 47:\n\t\t\t\tswitch (peek()) {\n\t\t\t\t\tcase 42: case 47:\n\t\t\t\t\t\tappend(comment(commenter(next(), caret()), root, parent, declarations), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcharacters += '/'\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t// {\n\t\t\tcase 123 * variable:\n\t\t\t\tpoints[index++] = strlen(characters) * ampersand\n\t\t\t// } ; \\0\n\t\t\tcase 125 * variable: case 59: case 0:\n\t\t\t\tswitch (character) {\n\t\t\t\t\t// \\0 }\n\t\t\t\t\tcase 0: case 125: scanning = 0\n\t\t\t\t\t// ;\n\t\t\t\t\tcase 59 + offset: if (ampersand == -1) characters = replace(characters, /\\f/g, '')\n\t\t\t\t\t\tif (property > 0 && (strlen(characters) - length))\n\t\t\t\t\t\t\tappend(property > 32 ? declaration(characters + ';', rule, parent, length - 1, declarations) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2, declarations), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @ ;\n\t\t\t\t\tcase 59: characters += ';'\n\t\t\t\t\t// { rule/at-rule\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tappend(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length, rulesets), rulesets)\n\n\t\t\t\t\t\tif (character === 123)\n\t\t\t\t\t\t\tif (offset === 0)\n\t\t\t\t\t\t\t\tparse(characters, root, reference, reference, props, rulesets, length, points, children)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tswitch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {\n\t\t\t\t\t\t\t\t\t// d l m s\n\t\t\t\t\t\t\t\t\tcase 100: case 108: case 109: case 115:\n\t\t\t\t\t\t\t\t\t\tparse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length, children), children), rules, children, length, points, rule ? props : children)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\tparse(characters, reference, reference, reference, [''], children, 0, points, children)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tindex = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo\n\t\t\t\tbreak\n\t\t\t// :\n\t\t\tcase 58:\n\t\t\t\tlength = 1 + strlen(characters), property = previous\n\t\t\tdefault:\n\t\t\t\tif (variable < 1)\n\t\t\t\t\tif (character == 123)\n\t\t\t\t\t\t--variable\n\t\t\t\t\telse if (character == 125 && variable++ == 0 && prev() == 125)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\tswitch (characters += from(character), character * variable) {\n\t\t\t\t\t// &\n\t\t\t\t\tcase 38:\n\t\t\t\t\t\tampersand = offset > 0 ? 1 : (characters += '\\f', -1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// ,\n\t\t\t\t\tcase 44:\n\t\t\t\t\t\tpoints[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @\n\t\t\t\t\tcase 64:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (peek() === 45)\n\t\t\t\t\t\t\tcharacters += delimit(next())\n\n\t\t\t\t\t\tatrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// -\n\t\t\t\t\tcase 45:\n\t\t\t\t\t\tif (previous === 45 && strlen(characters) == 2)\n\t\t\t\t\t\t\tvariable = 0\n\t\t\t\t}\n\t\t}\n\n\treturn rulesets\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} index\n * @param {number} offset\n * @param {string[]} rules\n * @param {number[]} points\n * @param {string} type\n * @param {string[]} props\n * @param {string[]} children\n * @param {number} length\n * @param {object[]} siblings\n * @return {object}\n */\nexport function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length, siblings) {\n\tvar post = offset - 1\n\tvar rule = offset === 0 ? rules : ['']\n\tvar size = sizeof(rule)\n\n\tfor (var i = 0, j = 0, k = 0; i < index; ++i)\n\t\tfor (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)\n\t\t\tif (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\\f/g, rule[x])))\n\t\t\t\tprops[k++] = z\n\n\treturn node(value, root, parent, offset === 0 ? RULESET : type, props, children, length, siblings)\n}\n\n/**\n * @param {number} value\n * @param {object} root\n * @param {object?} parent\n * @param {object[]} siblings\n * @return {object}\n */\nexport function comment (value, root, parent, siblings) {\n\treturn node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0, siblings)\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} length\n * @param {object[]} siblings\n * @return {object}\n */\nexport function declaration (value, root, parent, length, siblings) {\n\treturn node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length, siblings)\n}\n","var unitlessKeys = {\n animationIterationCount: 1,\n aspectRatio: 1,\n borderImageOutset: 1,\n borderImageSlice: 1,\n borderImageWidth: 1,\n boxFlex: 1,\n boxFlexGroup: 1,\n boxOrdinalGroup: 1,\n columnCount: 1,\n columns: 1,\n flex: 1,\n flexGrow: 1,\n flexPositive: 1,\n flexShrink: 1,\n flexNegative: 1,\n flexOrder: 1,\n gridRow: 1,\n gridRowEnd: 1,\n gridRowSpan: 1,\n gridRowStart: 1,\n gridColumn: 1,\n gridColumnEnd: 1,\n gridColumnSpan: 1,\n gridColumnStart: 1,\n msGridRow: 1,\n msGridRowSpan: 1,\n msGridColumn: 1,\n msGridColumnSpan: 1,\n fontWeight: 1,\n lineHeight: 1,\n opacity: 1,\n order: 1,\n orphans: 1,\n tabSize: 1,\n widows: 1,\n zIndex: 1,\n zoom: 1,\n WebkitLineClamp: 1,\n // SVG-related properties\n fillOpacity: 1,\n floodOpacity: 1,\n stopOpacity: 1,\n strokeDasharray: 1,\n strokeDashoffset: 1,\n strokeMiterlimit: 1,\n strokeOpacity: 1,\n strokeWidth: 1\n};\n\nexport { unitlessKeys as default };\n","declare let SC_DISABLE_SPEEDY: boolean | null | undefined;\ndeclare let __VERSION__: string;\n\nexport const SC_ATTR: string =\n (typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR)) ||\n 'data-styled';\n\nexport const SC_ATTR_ACTIVE = 'active';\nexport const SC_ATTR_VERSION = 'data-styled-version';\nexport const SC_VERSION = __VERSION__;\nexport const SPLITTER = '/*!sc*/\\n';\n\nexport const IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;\n\nexport const DISABLE_SPEEDY = Boolean(\n typeof SC_DISABLE_SPEEDY === 'boolean'\n ? SC_DISABLE_SPEEDY\n : typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n typeof process.env.REACT_APP_SC_DISABLE_SPEEDY !== 'undefined' &&\n process.env.REACT_APP_SC_DISABLE_SPEEDY !== ''\n ? process.env.REACT_APP_SC_DISABLE_SPEEDY === 'false'\n ? false\n : process.env.REACT_APP_SC_DISABLE_SPEEDY\n : typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n typeof process.env.SC_DISABLE_SPEEDY !== 'undefined' &&\n process.env.SC_DISABLE_SPEEDY !== ''\n ? process.env.SC_DISABLE_SPEEDY === 'false'\n ? false\n : process.env.SC_DISABLE_SPEEDY\n : process.env.NODE_ENV !== 'production'\n);\n\n// Shared empty execution context when generating static styles\nexport const STATIC_EXECUTION_CONTEXT = {};\n","import { Dict } from '../types';\n\nexport const EMPTY_ARRAY = Object.freeze([]) as Readonly;\nexport const EMPTY_OBJECT = Object.freeze({}) as Readonly>;\n","import { useRef } from 'react';\n\nconst invalidHookCallRe = /invalid hook call/i;\nconst seen = new Set();\n\nexport const checkDynamicCreation = (displayName: string, componentId?: string | undefined) => {\n if (process.env.NODE_ENV !== 'production') {\n const parsedIdString = componentId ? ` with the id of \"${componentId}\"` : '';\n const message =\n `The component ${displayName}${parsedIdString} has been created dynamically.\\n` +\n \"You may see this warning because you've called styled inside another component.\\n\" +\n 'To resolve this only create new StyledComponents outside of any render method and function component.';\n\n // If a hook is called outside of a component:\n // React 17 and earlier throw an error\n // React 18 and above use console.error\n\n const originalConsoleError = console.error;\n try {\n let didNotCallInvalidHook = true;\n console.error = (consoleErrorMessage, ...consoleErrorArgs) => {\n // The error here is expected, since we're expecting anything that uses `checkDynamicCreation` to\n // be called outside of a React component.\n if (invalidHookCallRe.test(consoleErrorMessage)) {\n didNotCallInvalidHook = false;\n // This shouldn't happen, but resets `warningSeen` if we had this error happen intermittently\n seen.delete(message);\n } else {\n originalConsoleError(consoleErrorMessage, ...consoleErrorArgs);\n }\n };\n // We purposefully call `useRef` outside of a component and expect it to throw\n // If it doesn't, then we're inside another component.\n useRef();\n\n if (didNotCallInvalidHook && !seen.has(message)) {\n console.warn(message);\n seen.add(message);\n }\n } catch (error) {\n // The error here is expected, since we're expecting anything that uses `checkDynamicCreation` to\n // be called outside of a React component.\n if (invalidHookCallRe.test((error as Error).message)) {\n // This shouldn't happen, but resets `warningSeen` if we had this error happen intermittently\n seen.delete(message);\n }\n } finally {\n console.error = originalConsoleError;\n }\n }\n};\n","import { DefaultTheme, ExecutionProps } from '../types';\nimport { EMPTY_OBJECT } from './empties';\n\nexport default function determineTheme(\n props: ExecutionProps,\n providedTheme?: DefaultTheme | undefined,\n defaultProps: { theme?: DefaultTheme | undefined } = EMPTY_OBJECT\n): DefaultTheme | undefined {\n return (props.theme !== defaultProps.theme && props.theme) || providedTheme || defaultProps.theme;\n}\n","// Thanks to ReactDOMFactories for this handy list!\n\nconst elements = [\n 'a',\n 'abbr',\n 'address',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'base',\n 'bdi',\n 'bdo',\n 'big',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'data',\n 'datalist',\n 'dd',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'div',\n 'dl',\n 'dt',\n 'em',\n 'embed',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'i',\n 'iframe',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'keygen',\n 'label',\n 'legend',\n 'li',\n 'link',\n 'main',\n 'map',\n 'mark',\n 'menu',\n 'menuitem',\n 'meta',\n 'meter',\n 'nav',\n 'noscript',\n 'object',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'param',\n 'picture',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'script',\n 'section',\n 'select',\n 'small',\n 'source',\n 'span',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'track',\n 'u',\n 'ul',\n 'use',\n 'var',\n 'video',\n 'wbr', // SVG\n 'circle',\n 'clipPath',\n 'defs',\n 'ellipse',\n 'foreignObject',\n 'g',\n 'image',\n 'line',\n 'linearGradient',\n 'marker',\n 'mask',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialGradient',\n 'rect',\n 'stop',\n 'svg',\n 'text',\n 'tspan',\n] as const;\n\nexport default new Set(elements);\nexport type SupportedHTMLElements = (typeof elements)[number];\n","// Source: https://www.w3.org/TR/cssom-1/#serialize-an-identifier\n// Control characters and non-letter first symbols are not supported\nconst escapeRegex = /[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~-]+/g;\n\nconst dashesAtEnds = /(^-|-$)/g;\n\n/**\n * TODO: Explore using CSS.escape when it becomes more available\n * in evergreen browsers.\n */\nexport default function escape(str: string) {\n return str // Replace all possible CSS selectors\n .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end\n .replace(dashesAtEnds, '');\n}\n","const AD_REPLACER_R = /(a)(d)/gi;\n\n/* This is the \"capacity\" of our alphabet i.e. 2x26 for all letters plus their capitalised\n * counterparts */\nconst charsLength = 52;\n\n/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */\nconst getAlphabeticChar = (code: number) => String.fromCharCode(code + (code > 25 ? 39 : 97));\n\n/* input a number, usually a hash and convert it to base-52 */\nexport default function generateAlphabeticName(code: number) {\n let name = '';\n let x;\n\n /* get a char and divide by alphabet-length */\n for (x = Math.abs(code); x > charsLength; x = (x / charsLength) | 0) {\n name = getAlphabeticChar(x % charsLength) + name;\n }\n\n return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');\n}\n","export const SEED = 5381;\n\n// When we have separate strings it's useful to run a progressive\n// version of djb2 where we pretend that we're still looping over\n// the same string\nexport const phash = (h: number, x: string) => {\n let i = x.length;\n\n while (i) {\n h = (h * 33) ^ x.charCodeAt(--i);\n }\n\n return h;\n};\n\n// This is a djb2 hashing function\nexport const hash = (x: string) => {\n return phash(SEED, x);\n};\n","import generateAlphabeticName from './generateAlphabeticName';\nimport { hash } from './hash';\n\nexport default function generateComponentId(str: string) {\n return generateAlphabeticName(hash(str) >>> 0);\n}\n","import { StyledTarget } from '../types';\n\nexport default function getComponentName(target: StyledTarget) {\n return (\n (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) ||\n (target as Exclude, string>).displayName ||\n (target as Function).name ||\n 'Component'\n );\n}\n","import { StyledTarget } from '../types';\n\nexport default function isTag(target: StyledTarget<'web'>): target is string {\n return (\n typeof target === 'string' &&\n (process.env.NODE_ENV !== 'production'\n ? target.charAt(0) === target.charAt(0).toLowerCase()\n : true)\n );\n}\n","import React from 'react';\nimport { AnyComponent } from '../types';\n\nconst hasSymbol = typeof Symbol === 'function' && Symbol.for;\n\n// copied from react-is\nconst REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nconst REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\n\n/**\n * Adapted from hoist-non-react-statics to avoid the react-is dependency.\n */\nconst REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true,\n};\n\nconst KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true,\n};\n\nconst FORWARD_REF_STATICS = {\n $$typeof: true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n};\n\nconst MEMO_STATICS = {\n $$typeof: true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true,\n};\n\nconst TYPE_STATICS = {\n [REACT_FORWARD_REF_TYPE]: FORWARD_REF_STATICS,\n [REACT_MEMO_TYPE]: MEMO_STATICS,\n};\n\ntype OmniComponent = AnyComponent;\n\n// adapted from react-is\nfunction isMemo(\n object: OmniComponent | React.MemoExoticComponent