supersub
Version:
Supersub JS Sdk
1,475 lines (1,430 loc) • 2.39 MB
JavaScript
'use strict';
var React = require('react');
var Modal = require('react-modal');
var aaCore = require('@alchemy/aa-core');
var aaAlchemy = require('@alchemy/aa-alchemy');
var aaAccounts = require('@alchemy/aa-accounts');
var reactAuth = require('@privy-io/react-auth');
var react = require('@phosphor-icons/react');
var reactSpinners = require('react-spinners');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.
// https://twitter.com/GabrielVergnaud/status/1622906834343366657
function execTyped(regex, string) {
const match = regex.exec(string);
return match?.groups;
}
// https://regexr.com/7f7rv
const tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/;
/**
* Formats {@link AbiParameter} to human-readable ABI parameter.
*
* @param abiParameter - ABI parameter
* @returns Human-readable ABI parameter
*
* @example
* const result = formatAbiParameter({ type: 'address', name: 'from' })
* // ^? const result: 'address from'
*/
function formatAbiParameter(abiParameter) {
let type = abiParameter.type;
if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {
type = '(';
const length = abiParameter.components.length;
for (let i = 0; i < length; i++) {
const component = abiParameter.components[i];
type += formatAbiParameter(component);
if (i < length - 1)
type += ', ';
}
const result = execTyped(tupleRegex, abiParameter.type);
type += `)${result?.array ?? ''}`;
return formatAbiParameter({
...abiParameter,
type,
});
}
// Add `indexed` to type if in `abiParameter`
if ('indexed' in abiParameter && abiParameter.indexed)
type = `${type} indexed`;
// Return human-readable ABI parameter
if (abiParameter.name)
return `${type} ${abiParameter.name}`;
return type;
}
/**
* Formats {@link AbiParameter}s to human-readable ABI parameters.
*
* @param abiParameters - ABI parameters
* @returns Human-readable ABI parameters
*
* @example
* const result = formatAbiParameters([
* // ^? const result: 'address from, uint256 tokenId'
* { type: 'address', name: 'from' },
* { type: 'uint256', name: 'tokenId' },
* ])
*/
function formatAbiParameters(abiParameters) {
let params = '';
const length = abiParameters.length;
for (let i = 0; i < length; i++) {
const abiParameter = abiParameters[i];
params += formatAbiParameter(abiParameter);
if (i !== length - 1)
params += ', ';
}
return params;
}
/**
* Formats ABI item (e.g. error, event, function) into human-readable ABI item
*
* @param abiItem - ABI item
* @returns Human-readable ABI item
*/
function formatAbiItem$1(abiItem) {
if (abiItem.type === 'function')
return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'
? ` ${abiItem.stateMutability}`
: ''}${abiItem.outputs.length
? ` returns (${formatAbiParameters(abiItem.outputs)})`
: ''}`;
else if (abiItem.type === 'event')
return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
else if (abiItem.type === 'error')
return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
else if (abiItem.type === 'constructor')
return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
else if (abiItem.type === 'fallback')
return 'fallback()';
return 'receive() external payable';
}
/**
* Retrieves and returns an action from the client (if exists), and falls
* back to the tree-shakable action.
*
* Useful for extracting overridden actions from a client (ie. if a consumer
* wants to override the `sendTransaction` implementation).
*/
function getAction(client, action,
// Some minifiers drop `Function.prototype.name`, meaning that `action.name`
// will not work. For that case, the consumer needs to pass the name explicitly.
name) {
return (params) => client[action.name || name]?.(params) ?? action(client, params);
}
function formatAbiItem(abiItem, { includeName = false } = {}) {
if (abiItem.type !== 'function' &&
abiItem.type !== 'event' &&
abiItem.type !== 'error')
throw new InvalidDefinitionTypeError(abiItem.type);
return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;
}
function formatAbiParams(params, { includeName = false } = {}) {
if (!params)
return '';
return params
.map((param) => formatAbiParam(param, { includeName }))
.join(includeName ? ', ' : ',');
}
function formatAbiParam(param, { includeName }) {
if (param.type.startsWith('tuple')) {
return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;
}
return param.type + (includeName && param.name ? ` ${param.name}` : '');
}
function isHex(value, { strict = true } = {}) {
if (!value)
return false;
if (typeof value !== 'string')
return false;
return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');
}
/**
* @description Retrieves the size of the value (in bytes).
*
* @param value The value (hex or byte array) to retrieve the size of.
* @returns The size of the value (in bytes).
*/
function size$2(value) {
if (isHex(value, { strict: false }))
return Math.ceil((value.length - 2) / 2);
return value.length;
}
const version$4 = '2.8.6';
const getUrl = (url) => url;
const getVersion$2 = () => `viem@${version$4}`;
let BaseError$2 = class BaseError extends Error {
constructor(shortMessage, args = {}) {
super();
Object.defineProperty(this, "details", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "docsPath", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "metaMessages", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "shortMessage", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'ViemError'
});
Object.defineProperty(this, "version", {
enumerable: true,
configurable: true,
writable: true,
value: getVersion$2()
});
const details = args.cause instanceof BaseError
? args.cause.details
: args.cause?.message
? args.cause.message
: args.details;
const docsPath = args.cause instanceof BaseError
? args.cause.docsPath || args.docsPath
: args.docsPath;
this.message = [
shortMessage || 'An error occurred.',
'',
...(args.metaMessages ? [...args.metaMessages, ''] : []),
...(docsPath
? [
`Docs: https://viem.sh${docsPath}${args.docsSlug ? `#${args.docsSlug}` : ''}`,
]
: []),
...(details ? [`Details: ${details}`] : []),
`Version: ${this.version}`,
].join('\n');
if (args.cause)
this.cause = args.cause;
this.details = details;
this.docsPath = docsPath;
this.metaMessages = args.metaMessages;
this.shortMessage = shortMessage;
}
walk(fn) {
return walk(this, fn);
}
};
function walk(err, fn) {
if (fn?.(err))
return err;
if (err && typeof err === 'object' && 'cause' in err)
return walk(err.cause, fn);
return fn ? null : err;
}
class AbiConstructorNotFoundError extends BaseError$2 {
constructor({ docsPath }) {
super([
'A constructor was not found on the ABI.',
'Make sure you are using the correct ABI and that the constructor exists on it.',
].join('\n'), {
docsPath,
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiConstructorNotFoundError'
});
}
}
class AbiConstructorParamsNotFoundError extends BaseError$2 {
constructor({ docsPath }) {
super([
'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',
'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',
].join('\n'), {
docsPath,
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiConstructorParamsNotFoundError'
});
}
}
class AbiEncodingArrayLengthMismatchError extends BaseError$2 {
constructor({ expectedLength, givenLength, type, }) {
super([
`ABI encoding array length mismatch for type ${type}.`,
`Expected length: ${expectedLength}`,
`Given length: ${givenLength}`,
].join('\n'));
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiEncodingArrayLengthMismatchError'
});
}
}
class AbiEncodingBytesSizeMismatchError extends BaseError$2 {
constructor({ expectedSize, value }) {
super(`Size of bytes "${value}" (bytes${size$2(value)}) does not match expected size (bytes${expectedSize}).`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiEncodingBytesSizeMismatchError'
});
}
}
class AbiEncodingLengthMismatchError extends BaseError$2 {
constructor({ expectedLength, givenLength, }) {
super([
'ABI encoding params/values length mismatch.',
`Expected length (params): ${expectedLength}`,
`Given length (values): ${givenLength}`,
].join('\n'));
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiEncodingLengthMismatchError'
});
}
}
class AbiFunctionNotFoundError extends BaseError$2 {
constructor(functionName, { docsPath } = {}) {
super([
`Function ${functionName ? `"${functionName}" ` : ''}not found on ABI.`,
'Make sure you are using the correct ABI and that the function exists on it.',
].join('\n'), {
docsPath,
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiFunctionNotFoundError'
});
}
}
class AbiItemAmbiguityError extends BaseError$2 {
constructor(x, y) {
super('Found ambiguous types in overloaded ABI items.', {
metaMessages: [
`\`${x.type}\` in \`${formatAbiItem(x.abiItem)}\`, and`,
`\`${y.type}\` in \`${formatAbiItem(y.abiItem)}\``,
'',
'These types encode differently and cannot be distinguished at runtime.',
'Remove one of the ambiguous items in the ABI.',
],
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'AbiItemAmbiguityError'
});
}
}
class BytesSizeMismatchError extends BaseError$2 {
constructor({ expectedSize, givenSize, }) {
super(`Expected bytes${expectedSize}, got bytes${givenSize}.`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'BytesSizeMismatchError'
});
}
}
class InvalidAbiEncodingTypeError extends BaseError$2 {
constructor(type, { docsPath }) {
super([
`Type "${type}" is not a valid encoding type.`,
'Please provide a valid ABI type.',
].join('\n'), { docsPath });
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'InvalidAbiEncodingType'
});
}
}
class InvalidArrayError extends BaseError$2 {
constructor(value) {
super([`Value "${value}" is not a valid array.`].join('\n'));
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'InvalidArrayError'
});
}
}
class InvalidDefinitionTypeError extends BaseError$2 {
constructor(type) {
super([
`"${type}" is not a valid definition type.`,
'Valid types: "function", "event", "error"',
].join('\n'));
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'InvalidDefinitionTypeError'
});
}
}
class SliceOffsetOutOfBoundsError extends BaseError$2 {
constructor({ offset, position, size, }) {
super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset "${offset}" is out-of-bounds (size: ${size}).`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'SliceOffsetOutOfBoundsError'
});
}
}
class SizeExceedsPaddingSizeError extends BaseError$2 {
constructor({ size, targetSize, type, }) {
super(`${type.charAt(0).toUpperCase()}${type
.slice(1)
.toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'SizeExceedsPaddingSizeError'
});
}
}
function pad(hexOrBytes, { dir, size = 32 } = {}) {
if (typeof hexOrBytes === 'string')
return padHex(hexOrBytes, { dir, size });
return padBytes(hexOrBytes, { dir, size });
}
function padHex(hex_, { dir, size = 32 } = {}) {
if (size === null)
return hex_;
const hex = hex_.replace('0x', '');
if (hex.length > size * 2)
throw new SizeExceedsPaddingSizeError({
size: Math.ceil(hex.length / 2),
targetSize: size,
type: 'hex',
});
return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;
}
function padBytes(bytes, { dir, size = 32 } = {}) {
if (size === null)
return bytes;
if (bytes.length > size)
throw new SizeExceedsPaddingSizeError({
size: bytes.length,
targetSize: size,
type: 'bytes',
});
const paddedBytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
const padEnd = dir === 'right';
paddedBytes[padEnd ? i : size - i - 1] =
bytes[padEnd ? i : bytes.length - i - 1];
}
return paddedBytes;
}
class IntegerOutOfRangeError extends BaseError$2 {
constructor({ max, min, signed, size, value, }) {
super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'IntegerOutOfRangeError'
});
}
}
class SizeOverflowError extends BaseError$2 {
constructor({ givenSize, maxSize }) {
super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'SizeOverflowError'
});
}
}
function assertSize(hexOrBytes, { size }) {
if (size$2(hexOrBytes) > size)
throw new SizeOverflowError({
givenSize: size$2(hexOrBytes),
maxSize: size,
});
}
/**
* Decodes a hex value into a bigint.
*
* - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint
*
* @param hex Hex value to decode.
* @param opts Options.
* @returns BigInt value.
*
* @example
* import { hexToBigInt } from 'viem'
* const data = hexToBigInt('0x1a4', { signed: true })
* // 420n
*
* @example
* import { hexToBigInt } from 'viem'
* const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
* // 420n
*/
function hexToBigInt(hex, opts = {}) {
const { signed } = opts;
if (opts.size)
assertSize(hex, { size: opts.size });
const value = BigInt(hex);
if (!signed)
return value;
const size = (hex.length - 2) / 2;
const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;
if (value <= max)
return value;
return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;
}
/**
* Decodes a hex string into a number.
*
* - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber
*
* @param hex Hex value to decode.
* @param opts Options.
* @returns Number value.
*
* @example
* import { hexToNumber } from 'viem'
* const data = hexToNumber('0x1a4')
* // 420
*
* @example
* import { hexToNumber } from 'viem'
* const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
* // 420
*/
function hexToNumber$1(hex, opts = {}) {
return Number(hexToBigInt(hex, opts));
}
const hexes$1 = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
/**
* Encodes a string, number, bigint, or ByteArray into a hex string
*
* - Docs: https://viem.sh/docs/utilities/toHex
* - Example: https://viem.sh/docs/utilities/toHex#usage
*
* @param value Value to encode.
* @param opts Options.
* @returns Hex value.
*
* @example
* import { toHex } from 'viem'
* const data = toHex('Hello world')
* // '0x48656c6c6f20776f726c6421'
*
* @example
* import { toHex } from 'viem'
* const data = toHex(420)
* // '0x1a4'
*
* @example
* import { toHex } from 'viem'
* const data = toHex('Hello world', { size: 32 })
* // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
*/
function toHex(value, opts = {}) {
if (typeof value === 'number' || typeof value === 'bigint')
return numberToHex(value, opts);
if (typeof value === 'string') {
return stringToHex(value, opts);
}
if (typeof value === 'boolean')
return boolToHex(value, opts);
return bytesToHex$1(value, opts);
}
/**
* Encodes a boolean into a hex string
*
* - Docs: https://viem.sh/docs/utilities/toHex#booltohex
*
* @param value Value to encode.
* @param opts Options.
* @returns Hex value.
*
* @example
* import { boolToHex } from 'viem'
* const data = boolToHex(true)
* // '0x1'
*
* @example
* import { boolToHex } from 'viem'
* const data = boolToHex(false)
* // '0x0'
*
* @example
* import { boolToHex } from 'viem'
* const data = boolToHex(true, { size: 32 })
* // '0x0000000000000000000000000000000000000000000000000000000000000001'
*/
function boolToHex(value, opts = {}) {
const hex = `0x${Number(value)}`;
if (typeof opts.size === 'number') {
assertSize(hex, { size: opts.size });
return pad(hex, { size: opts.size });
}
return hex;
}
/**
* Encodes a bytes array into a hex string
*
* - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
*
* @param value Value to encode.
* @param opts Options.
* @returns Hex value.
*
* @example
* import { bytesToHex } from 'viem'
* const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
* // '0x48656c6c6f20576f726c6421'
*
* @example
* import { bytesToHex } from 'viem'
* const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
* // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
*/
function bytesToHex$1(value, opts = {}) {
let string = '';
for (let i = 0; i < value.length; i++) {
string += hexes$1[value[i]];
}
const hex = `0x${string}`;
if (typeof opts.size === 'number') {
assertSize(hex, { size: opts.size });
return pad(hex, { dir: 'right', size: opts.size });
}
return hex;
}
/**
* Encodes a number or bigint into a hex string
*
* - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
*
* @param value Value to encode.
* @param opts Options.
* @returns Hex value.
*
* @example
* import { numberToHex } from 'viem'
* const data = numberToHex(420)
* // '0x1a4'
*
* @example
* import { numberToHex } from 'viem'
* const data = numberToHex(420, { size: 32 })
* // '0x00000000000000000000000000000000000000000000000000000000000001a4'
*/
function numberToHex(value_, opts = {}) {
const { signed, size } = opts;
const value = BigInt(value_);
let maxValue;
if (size) {
if (signed)
maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;
else
maxValue = 2n ** (BigInt(size) * 8n) - 1n;
}
else if (typeof value_ === 'number') {
maxValue = BigInt(Number.MAX_SAFE_INTEGER);
}
const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;
if ((maxValue && value > maxValue) || value < minValue) {
const suffix = typeof value_ === 'bigint' ? 'n' : '';
throw new IntegerOutOfRangeError({
max: maxValue ? `${maxValue}${suffix}` : undefined,
min: `${minValue}${suffix}`,
signed,
size,
value: `${value_}${suffix}`,
});
}
const hex = `0x${(signed && value < 0
? (1n << BigInt(size * 8)) + BigInt(value)
: value).toString(16)}`;
if (size)
return pad(hex, { size });
return hex;
}
const encoder$1 = /*#__PURE__*/ new TextEncoder();
/**
* Encodes a UTF-8 string into a hex string
*
* - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
*
* @param value Value to encode.
* @param opts Options.
* @returns Hex value.
*
* @example
* import { stringToHex } from 'viem'
* const data = stringToHex('Hello World!')
* // '0x48656c6c6f20576f726c6421'
*
* @example
* import { stringToHex } from 'viem'
* const data = stringToHex('Hello World!', { size: 32 })
* // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
*/
function stringToHex(value_, opts = {}) {
const value = encoder$1.encode(value_);
return bytesToHex$1(value, opts);
}
const encoder = /*#__PURE__*/ new TextEncoder();
/**
* Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
*
* - Docs: https://viem.sh/docs/utilities/toBytes
* - Example: https://viem.sh/docs/utilities/toBytes#usage
*
* @param value Value to encode.
* @param opts Options.
* @returns Byte array value.
*
* @example
* import { toBytes } from 'viem'
* const data = toBytes('Hello world')
* // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
*
* @example
* import { toBytes } from 'viem'
* const data = toBytes(420)
* // Uint8Array([1, 164])
*
* @example
* import { toBytes } from 'viem'
* const data = toBytes(420, { size: 4 })
* // Uint8Array([0, 0, 1, 164])
*/
function toBytes$3(value, opts = {}) {
if (typeof value === 'number' || typeof value === 'bigint')
return numberToBytes(value, opts);
if (typeof value === 'boolean')
return boolToBytes(value, opts);
if (isHex(value))
return hexToBytes$1(value, opts);
return stringToBytes(value, opts);
}
/**
* Encodes a boolean into a byte array.
*
* - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
*
* @param value Boolean value to encode.
* @param opts Options.
* @returns Byte array value.
*
* @example
* import { boolToBytes } from 'viem'
* const data = boolToBytes(true)
* // Uint8Array([1])
*
* @example
* import { boolToBytes } from 'viem'
* const data = boolToBytes(true, { size: 32 })
* // 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])
*/
function boolToBytes(value, opts = {}) {
const bytes = new Uint8Array(1);
bytes[0] = Number(value);
if (typeof opts.size === 'number') {
assertSize(bytes, { size: opts.size });
return pad(bytes, { size: opts.size });
}
return bytes;
}
// We use very optimized technique to convert hex string to byte array
const charCodeMap = {
zero: 48,
nine: 57,
A: 65,
F: 70,
a: 97,
f: 102,
};
function charCodeToBase16(char) {
if (char >= charCodeMap.zero && char <= charCodeMap.nine)
return char - charCodeMap.zero;
if (char >= charCodeMap.A && char <= charCodeMap.F)
return char - (charCodeMap.A - 10);
if (char >= charCodeMap.a && char <= charCodeMap.f)
return char - (charCodeMap.a - 10);
return undefined;
}
/**
* Encodes a hex string into a byte array.
*
* - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
*
* @param hex Hex string to encode.
* @param opts Options.
* @returns Byte array value.
*
* @example
* import { hexToBytes } from 'viem'
* const data = hexToBytes('0x48656c6c6f20776f726c6421')
* // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
*
* @example
* import { hexToBytes } from 'viem'
* const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
* // 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])
*/
function hexToBytes$1(hex_, opts = {}) {
let hex = hex_;
if (opts.size) {
assertSize(hex, { size: opts.size });
hex = pad(hex, { dir: 'right', size: opts.size });
}
let hexString = hex.slice(2);
if (hexString.length % 2)
hexString = `0${hexString}`;
const length = hexString.length / 2;
const bytes = new Uint8Array(length);
for (let index = 0, j = 0; index < length; index++) {
const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
if (nibbleLeft === undefined || nibbleRight === undefined) {
throw new BaseError$2(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
}
bytes[index] = nibbleLeft * 16 + nibbleRight;
}
return bytes;
}
/**
* Encodes a number into a byte array.
*
* - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
*
* @param value Number to encode.
* @param opts Options.
* @returns Byte array value.
*
* @example
* import { numberToBytes } from 'viem'
* const data = numberToBytes(420)
* // Uint8Array([1, 164])
*
* @example
* import { numberToBytes } from 'viem'
* const data = numberToBytes(420, { size: 4 })
* // Uint8Array([0, 0, 1, 164])
*/
function numberToBytes(value, opts) {
const hex = numberToHex(value, opts);
return hexToBytes$1(hex);
}
/**
* Encodes a UTF-8 string into a byte array.
*
* - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
*
* @param value String to encode.
* @param opts Options.
* @returns Byte array value.
*
* @example
* import { stringToBytes } from 'viem'
* const data = stringToBytes('Hello world!')
* // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
*
* @example
* import { stringToBytes } from 'viem'
* const data = stringToBytes('Hello world!', { size: 32 })
* // 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])
*/
function stringToBytes(value, opts = {}) {
const bytes = encoder.encode(value);
if (typeof opts.size === 'number') {
assertSize(bytes, { size: opts.size });
return pad(bytes, { dir: 'right', size: opts.size });
}
return bytes;
}
function number$2(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bytes$2(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error('Expected Uint8Array');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function exists$2(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
function output$2(out, instance) {
bytes$2(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n$1 = /* @__PURE__ */ BigInt(32);
// We are not using BigUint64Array, because they are extremely slow as per 2022
function fromBig$1(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64$1), l: Number((n >> _32n$1) & U32_MASK64$1) };
return { h: Number((n >> _32n$1) & U32_MASK64$1) | 0, l: Number(n & U32_MASK64$1) | 0 };
}
function split$2(lst, le = false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig$1(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
// Left rotate for Shift in [1, 32)
const rotlSH$1 = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL$1 = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH$1 = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL$1 = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated, we can just drop the import.
const u8a$3 = (a) => a instanceof Uint8Array;
const u32$1 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
// big-endian hardware is rare. Just in case someone still decides to run hashes:
// early-throw an error because we don't support BE yet.
const isLE$2 = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
if (!isLE$2)
throw new Error('Non little-endian hardware is not supported');
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
function utf8ToBytes$3(str) {
if (typeof str !== 'string')
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes$2(data) {
if (typeof data === 'string')
data = utf8ToBytes$3(data);
if (!u8a$3(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
// For runtime check if class implements interface
let Hash$2 = class Hash {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
function wrapConstructor$2(hashCons) {
const hashC = (msg) => hashCons().update(toBytes$2(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
// It's called a sponge function.
// Various per round constants calculations
const [SHA3_PI$1, SHA3_ROTL$1, _SHA3_IOTA$1] = [[], [], []];
const _0n$5 = /* @__PURE__ */ BigInt(0);
const _1n$6 = /* @__PURE__ */ BigInt(1);
const _2n$4 = /* @__PURE__ */ BigInt(2);
const _7n$1 = /* @__PURE__ */ BigInt(7);
const _256n$1 = /* @__PURE__ */ BigInt(256);
const _0x71n$1 = /* @__PURE__ */ BigInt(0x71);
for (let round = 0, R = _1n$6, x = 1, y = 0; round < 24; round++) {
// Pi
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI$1.push(2 * (5 * y + x));
// Rotational
SHA3_ROTL$1.push((((round + 1) * (round + 2)) / 2) % 64);
// Iota
let t = _0n$5;
for (let j = 0; j < 7; j++) {
R = ((R << _1n$6) ^ ((R >> _7n$1) * _0x71n$1)) % _256n$1;
if (R & _2n$4)
t ^= _1n$6 << ((_1n$6 << /* @__PURE__ */ BigInt(j)) - _1n$6);
}
_SHA3_IOTA$1.push(t);
}
const [SHA3_IOTA_H$1, SHA3_IOTA_L$1] = /* @__PURE__ */ split$2(_SHA3_IOTA$1, true);
// Left rotation (without 0, 32, 64)
const rotlH$1 = (h, l, s) => (s > 32 ? rotlBH$1(h, l, s) : rotlSH$1(h, l, s));
const rotlL$1 = (h, l, s) => (s > 32 ? rotlBL$1(h, l, s) : rotlSL$1(h, l, s));
// Same as keccakf1600, but allows to skip some rounds
function keccakP$1(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
for (let round = 24 - rounds; round < 24; round++) {
// Theta θ
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH$1(B0, B1, 1) ^ B[idx1];
const Tl = rotlL$1(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
// Rho (ρ) and Pi (π)
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL$1[t];
const Th = rotlH$1(curH, curL, shift);
const Tl = rotlL$1(curH, curL, shift);
const PI = SHA3_PI$1[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
// Chi (χ)
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
// Iota (ι)
s[0] ^= SHA3_IOTA_H$1[round];
s[1] ^= SHA3_IOTA_L$1[round];
}
B.fill(0);
}
let Keccak$1 = class Keccak extends Hash$2 {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
// Can be passed from user as dkLen
number$2(outputLen);
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
if (0 >= this.blockLen || this.blockLen >= 200)
throw new Error('Sha3 supports only keccak-f1600 function');
this.state = new Uint8Array(200);
this.state32 = u32$1(this.state);
}
keccak() {
keccakP$1(this.state32, this.rounds);
this.posOut = 0;
this.pos = 0;
}
update(data) {
exists$2(this);
const { blockLen, state } = this;
data = toBytes$2(data);
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
// Do the padding
state[pos] ^= suffix;
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 0x80;
this.keccak();
}
writeInto(out) {
exists$2(this, false);
bytes$2(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
if (!this.enableXOF)
throw new Error('XOF is not possible for this instance');
return this.writeInto(out);
}
xof(bytes) {
number$2(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
output$2(out, this);
if (this.finished)
throw new Error('digest() was already called');
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
this.state.fill(0);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
// Suffix can change in cSHAKE
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
};
const gen$1 = (suffix, blockLen, outputLen) => wrapConstructor$2(() => new Keccak$1(blockLen, suffix, outputLen));
/**
* keccak-256 hash function. Different from SHA3-256.
* @param message - that would be hashed
*/
const keccak_256$1 = /* @__PURE__ */ gen$1(0x01, 136, 256 / 8);
function keccak256$1(value, to_) {
const to = to_ || 'hex';
const bytes = keccak_256$1(isHex(value, { strict: false }) ? toBytes$3(value) : value);
if (to === 'bytes')
return bytes;
return toHex(bytes);
}
const hash$1 = (value) => keccak256$1(toBytes$3(value));
function hashSignature(sig) {
return hash$1(sig);
}
function normalizeSignature(signature) {
let active = true;
let current = '';
let level = 0;
let result = '';
let valid = false;
for (let i = 0; i < signature.length; i++) {
const char = signature[i];
// If the character is a separator, we want to reactivate.
if (['(', ')', ','].includes(char))
active = true;
// If the character is a "level" token, we want to increment/decrement.
if (char === '(')
level++;
if (char === ')')
level--;
// If we aren't active, we don't want to mutate the result.
if (!active)
continue;
// If level === 0, we are at the definition level.
if (level === 0) {
if (char === ' ' && ['event', 'function', ''].includes(result))
result = '';
else {
result += char;
// If we are at the end of the definition, we must be finished.
if (char === ')') {
valid = true;
break;
}
}
continue;
}
// Ignore spaces
if (char === ' ') {
// If the previous character is a separator, and the current section isn't empty, we want to deactivate.
if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {
current = '';
active = false;
}
continue;
}
result += char;
current += char;
}
if (!valid)
throw new BaseError$2('Unable to normalize signature.');
return result;
}
/**
* Returns the signature for a given function or event definition.
*
* @example
* const signature = toSignature('function ownerOf(uint256 tokenId)')
* // 'ownerOf(uint256)'
*
* @example
* const signature_3 = toSignature({
* name: 'ownerOf',
* type: 'function',
* inputs: [{ name: 'tokenId', type: 'uint256' }],
* outputs: [],
* stateMutability: 'view',
* })
* // 'ownerOf(uint256)'
*/
const toSignature = (def) => {
const def_ = (() => {
if (typeof def === 'string')
return def;
return formatAbiItem$1(def);
})();
return normalizeSignature(def_);
};
/**
* Returns the hash (of the function/event signature) for a given event or function definition.
*/
function toSignatureHash(fn) {
return hashSignature(toSignature(fn));
}
/**
* Returns the event selector for a given event definition.
*
* @example
* const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')
* // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
*/
const toEventSelector = toSignatureHash;
class InvalidAddressError extends BaseError$2 {
constructor({ address }) {
super(`Address "${address}" is invalid.`, {
metaMessages: [
'- Address must be a hex value of 20 bytes (40 hex characters).',
'- Address must match its checksum counterpart.',
],
});
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: 'InvalidAddressError'
});
}
}
/**
* Map with a LRU (Least recently used) policy.
*
* @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
*/
class LruMap extends Map {
constructor(size) {
super();
Object.defineProperty(this, "maxSize", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.maxSize = size;
}
set(key, value) {
super.set(key, value);
if (this.maxSize && this.size > this.maxSize)
this.delete(this.keys().next().value);
return this;
}
}
function checksumAddress(address_, chainId) {
const hexAddress = chainId
? `${chainId}${address_.toLowerCase()}`
: address_.substring(2).toLowerCase();
const hash = keccak256$1(stringToBytes(hexAddress), 'bytes');
const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split('');
for (let i = 0; i < 40; i += 2) {
if (hash[i >> 1] >> 4 >= 8 && address[i]) {
address[i] = address[i].toUpperCase();
}
if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {
address[i + 1] = address[i + 1].toUpperCase();
}
}
return `0x${address.join('')}`;
}
function getAddress$1(address, chainId) {
if (!isAddress(address))
throw new InvalidAddressError({ address });
return checksumAddress(address, chainId);
}
const addressRegex = /^0x[a-fA-F0-9]{40}$/;
const isAddressCache = /*#__PURE__*/ new LruMap(8192);
function isAddress(address, { strict = true } = {}) {
if (isAddressCache.has(address))
return isAddressCache.get(address);
const result = (() => {
if (!addressRegex.test(address))
return false;
if (address.toLowerCase() === address)
return true;
if (strict)
return checksumAddress(address) === address;
return true;
})();
isAddressCache.set(address, result);
return result;
}
function concat$1(values) {
if (typeof values[0] === 'string')
return concatHex(values);
return concatBytes$2(values);
}
function concatBytes$2(values) {
let length = 0;
for (const arr of values) {
length += arr.length;
}
const result = new Uint8Array(length);
let offset = 0;
for (const arr of values) {
result.set(arr, offset);
offset += arr.length;