UNPKG

@etherspot/remote-signer

Version:

Etherspot Permissioned Signer SDK - signs the UserOp with SessionKey and sends it to the Bundler

1,577 lines (1,529 loc) 161 kB
import { AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingLengthMismatchError, AbiEventNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, BaseError, BytesSizeMismatchError, CallExecutionError, ChainDisconnectedError, ChainMismatchError, ChainNotFoundError, ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, FeeCapTooHighError, HttpRequestError, InternalRpcError, InvalidAddressError, InvalidChainIdError, InvalidInputRpcError, InvalidLegacyVError, InvalidParamsRpcError, InvalidRequestRpcError, InvalidSerializableTransactionError, InvalidStorageKeySizeError, JsonRpcVersionUnsupportedError, LimitExceededRpcError, LruMap, MethodNotFoundRpcError, MethodNotSupportedRpcError, ParseRpcError, PositionOutOfBoundsError, ProviderDisconnectedError, RawContractError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, RpcRequestError, SwitchChainError, TimeoutError, TipAboveFeeCapError, TransactionExecutionError, TransactionNotFoundError, TransactionReceiptNotFoundError, TransactionRejectedRpcError, UnauthorizedProviderError, UnknownNodeError, UnknownRpcError, UnsupportedPackedAbiType, UnsupportedProviderMethodError, UserRejectedRequestError, WaitForTransactionReceiptTimeoutError, addressResolverAbi, assertRequest, boolToHex, bytesToHex, call, checksumAddress, concat, concatHex, createBatchScheduler, createCursor, decodeAbiParameters, decodeFunctionResult, defineFormatter, encodeAbiParameters, encodeDeployData, encodeFunctionData, extract, formatAbiItem, formatEther, formatGwei, formatTransactionRequest, getAbiItem, getAddress, getChainContractAddress, getNodeError, hexToBigInt, hexToBytes, hexToNumber, isAddress, isAddressEqual, isHex, keccak256, multicall3Abi, numberToHex, pad, panicReasons, parseAccount, prettyPrint, serializeStateOverride, size, slice, sliceHex, stringToBytes, stringToHex, stringify, textResolverAbi, toBytes, toEventSelector, toHex, trim, universalResolverResolveAbi, universalResolverReverseAbi, universalSignatureValidatorAbi, universalSignatureValidatorByteCode } from "./chunk-VPBLFL5G.mjs"; import { equalBytes, secp256k1, sha256 } from "./chunk-FHDGUR6E.mjs"; // node_modules/viem/_esm/utils/chain/defineChain.js function defineChain(chain) { return { formatters: void 0, fees: void 0, serializers: void 0, ...chain }; } // node_modules/viem/_esm/errors/transport.js var UrlRequiredError = class extends BaseError { constructor() { super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { docsPath: "/docs/clients/intro" }); } }; // node_modules/viem/_esm/utils/promise/withTimeout.js function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) { return new Promise((resolve, reject) => { ; (async () => { let timeoutId; try { const controller = new AbortController(); if (timeout > 0) { timeoutId = setTimeout(() => { if (signal) { controller.abort(); } else { reject(errorInstance); } }, timeout); } resolve(await fn({ signal: controller?.signal || null })); } catch (err) { if (err?.name === "AbortError") reject(errorInstance); reject(err); } finally { clearTimeout(timeoutId); } })(); }); } // node_modules/viem/_esm/utils/rpc/id.js function createIdStore() { return { current: 0, take() { return this.current++; }, reset() { this.current = 0; } }; } var idCache = /* @__PURE__ */ createIdStore(); // node_modules/viem/_esm/utils/rpc/http.js function getHttpRpcClient(url, options = {}) { return { async request(params) { const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; const fetchOptions = { ...options.fetchOptions ?? {}, ...params.fetchOptions ?? {} }; const { headers, method, signal: signal_ } = fetchOptions; try { const response = await withTimeout(async ({ signal }) => { const init = { ...fetchOptions, body: Array.isArray(body) ? stringify(body.map((body2) => ({ jsonrpc: "2.0", id: body2.id ?? idCache.take(), ...body2 }))) : stringify({ jsonrpc: "2.0", id: body.id ?? idCache.take(), ...body }), headers: { ...headers, "Content-Type": "application/json" }, method: method || "POST", signal: signal_ || (timeout > 0 ? signal : null) }; const request = new Request(url, init); if (onRequest) await onRequest(request); const response2 = await fetch(url, init); return response2; }, { errorInstance: new TimeoutError({ body, url }), timeout, signal: true }); if (onResponse) await onResponse(response); let data; if (response.headers.get("Content-Type")?.startsWith("application/json")) data = await response.json(); else { data = await response.text(); data = JSON.parse(data || "{}"); } if (!response.ok) { throw new HttpRequestError({ body, details: stringify(data.error) || response.statusText, headers: response.headers, status: response.status, url }); } return data; } catch (err) { if (err instanceof HttpRequestError) throw err; if (err instanceof TimeoutError) throw err; throw new HttpRequestError({ body, details: err.message, url }); } } }; } // node_modules/viem/_esm/utils/promise/withDedupe.js var promiseCache = /* @__PURE__ */ new LruMap(8192); function withDedupe(fn, { enabled = true, id }) { if (!enabled || !id) return fn(); if (promiseCache.get(id)) return promiseCache.get(id); const promise = fn().finally(() => promiseCache.delete(id)); promiseCache.set(id, promise); return promise; } // node_modules/viem/_esm/utils/wait.js async function wait(time) { return new Promise((res) => setTimeout(res, time)); } // node_modules/viem/_esm/utils/promise/withRetry.js function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { return new Promise((resolve, reject) => { const attemptRetry = async ({ count = 0 } = {}) => { const retry = async ({ error }) => { const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; if (delay) await wait(delay); attemptRetry({ count: count + 1 }); }; try { const data = await fn(); resolve(data); } catch (err) { if (count < retryCount && await shouldRetry2({ count, error: err })) return retry({ error: err }); reject(err); } }; attemptRetry(); }); } // node_modules/viem/_esm/utils/buildRequest.js function buildRequest(request, options = {}) { return async (args, overrideOptions = {}) => { const { dedupe = false, retryDelay = 150, retryCount = 3, uid: uid2 } = { ...options, ...overrideOptions }; const requestId = dedupe ? keccak256(stringToHex(`${uid2}.${stringify(args)}`)) : void 0; return withDedupe(() => withRetry(async () => { try { return await request(args); } catch (err_) { const err = err_; switch (err.code) { // -32700 case ParseRpcError.code: throw new ParseRpcError(err); // -32600 case InvalidRequestRpcError.code: throw new InvalidRequestRpcError(err); // -32601 case MethodNotFoundRpcError.code: throw new MethodNotFoundRpcError(err); // -32602 case InvalidParamsRpcError.code: throw new InvalidParamsRpcError(err); // -32603 case InternalRpcError.code: throw new InternalRpcError(err); // -32000 case InvalidInputRpcError.code: throw new InvalidInputRpcError(err); // -32001 case ResourceNotFoundRpcError.code: throw new ResourceNotFoundRpcError(err); // -32002 case ResourceUnavailableRpcError.code: throw new ResourceUnavailableRpcError(err); // -32003 case TransactionRejectedRpcError.code: throw new TransactionRejectedRpcError(err); // -32004 case MethodNotSupportedRpcError.code: throw new MethodNotSupportedRpcError(err); // -32005 case LimitExceededRpcError.code: throw new LimitExceededRpcError(err); // -32006 case JsonRpcVersionUnsupportedError.code: throw new JsonRpcVersionUnsupportedError(err); // 4001 case UserRejectedRequestError.code: throw new UserRejectedRequestError(err); // 4100 case UnauthorizedProviderError.code: throw new UnauthorizedProviderError(err); // 4200 case UnsupportedProviderMethodError.code: throw new UnsupportedProviderMethodError(err); // 4900 case ProviderDisconnectedError.code: throw new ProviderDisconnectedError(err); // 4901 case ChainDisconnectedError.code: throw new ChainDisconnectedError(err); // 4902 case SwitchChainError.code: throw new SwitchChainError(err); // CAIP-25: User Rejected Error // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25 case 5e3: throw new UserRejectedRequestError(err); default: if (err_ instanceof BaseError) throw err_; throw new UnknownRpcError(err); } } }, { delay: ({ count, error }) => { if (error && error instanceof HttpRequestError) { const retryAfter = error?.headers?.get("Retry-After"); if (retryAfter?.match(/\d/)) return Number.parseInt(retryAfter) * 1e3; } return ~~(1 << count) * retryDelay; }, retryCount, shouldRetry: ({ error }) => shouldRetry(error) }), { enabled: dedupe, id: requestId }); }; } function shouldRetry(error) { if ("code" in error && typeof error.code === "number") { if (error.code === -1) return true; if (error.code === LimitExceededRpcError.code) return true; if (error.code === InternalRpcError.code) return true; return false; } if (error instanceof HttpRequestError && error.status) { if (error.status === 403) return true; if (error.status === 408) return true; if (error.status === 413) return true; if (error.status === 429) return true; if (error.status === 500) return true; if (error.status === 502) return true; if (error.status === 503) return true; if (error.status === 504) return true; return false; } return true; } // node_modules/viem/_esm/utils/uid.js var size2 = 256; var index = size2; var buffer; function uid(length = 11) { if (!buffer || index + length > size2 * 2) { buffer = ""; index = 0; for (let i = 0; i < size2; i++) { buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); } } return buffer.substring(index, index++ + length); } // node_modules/viem/_esm/clients/transports/createTransport.js function createTransport({ key, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { const uid2 = uid(); return { config: { key, name, request, retryCount, retryDelay, timeout, type }, request: buildRequest(request, { retryCount, retryDelay, uid: uid2 }), value }; } // node_modules/viem/_esm/clients/transports/http.js function http(url, config = {}) { const { batch, fetchOptions, key = "http", name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay } = config; return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; const retryCount = config.retryCount ?? retryCount_; const timeout = timeout_ ?? config.timeout ?? 1e4; const url_ = url || chain?.rpcUrls.default.http[0]; if (!url_) throw new UrlRequiredError(); const rpcClient = getHttpRpcClient(url_, { fetchOptions, onRequest: onFetchRequest, onResponse: onFetchResponse, timeout }); return createTransport({ key, name, async request({ method, params }) { const body = { method, params }; const { schedule } = createBatchScheduler({ id: url_, wait: wait2, shouldSplitBatch(requests) { return requests.length > batchSize; }, fn: (body2) => rpcClient.request({ body: body2 }), sort: (a, b) => a.id - b.id }); const fn = async (body2) => batch ? schedule(body2) : [ await rpcClient.request({ body: body2 }) ]; const [{ error, result }] = await fn(body); if (error) throw new RpcRequestError({ body, error, url: url_ }); return result; }, retryCount, retryDelay, timeout, type: "http" }, { fetchOptions, url: url_ }); }; } // node_modules/viem/_esm/utils/chain/extractChain.js function extractChain({ chains, id }) { return chains.find((chain) => chain.id === id); } // node_modules/viem/_esm/utils/regex.js var arrayRegex = /^(.*)\[([0-9]*)\]$/; var bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; var integerRegex = /^(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)?$/; // node_modules/viem/_esm/utils/abi/encodePacked.js function encodePacked(types, values) { if (types.length !== values.length) throw new AbiEncodingLengthMismatchError({ expectedLength: types.length, givenLength: values.length }); const data = []; for (let i = 0; i < types.length; i++) { const type = types[i]; const value = values[i]; data.push(encode(type, value)); } return concatHex(data); } function encode(type, value, isArray = false) { if (type === "address") { const address = value; if (!isAddress(address)) throw new InvalidAddressError({ address }); return pad(address.toLowerCase(), { size: isArray ? 32 : null }); } if (type === "string") return stringToHex(value); if (type === "bytes") return value; if (type === "bool") return pad(boolToHex(value), { size: isArray ? 32 : 1 }); const intMatch = type.match(integerRegex); if (intMatch) { const [_type, baseType, bits = "256"] = intMatch; const size3 = Number.parseInt(bits) / 8; return numberToHex(value, { size: isArray ? 32 : size3, signed: baseType === "int" }); } const bytesMatch = type.match(bytesRegex); if (bytesMatch) { const [_type, size3] = bytesMatch; if (Number.parseInt(size3) !== (value.length - 2) / 2) throw new BytesSizeMismatchError({ expectedSize: Number.parseInt(size3), givenSize: (value.length - 2) / 2 }); return pad(value, { dir: "right", size: isArray ? 32 : null }); } const arrayMatch = type.match(arrayRegex); if (arrayMatch && Array.isArray(value)) { const [_type, childType] = arrayMatch; const data = []; for (let i = 0; i < value.length; i++) { data.push(encode(childType, value[i], true)); } if (data.length === 0) return "0x"; return concatHex(data); } throw new UnsupportedPackedAbiType(type); } // node_modules/viem/_esm/utils/data/isBytes.js function isBytes(value) { if (!value) return false; if (typeof value !== "object") return false; if (!("BYTES_PER_ELEMENT" in value)) return false; return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array"; } // node_modules/viem/_esm/utils/signature/serializeSignature.js function serializeSignature({ r, s, v, yParity }) { const yParity_ = (() => { if (yParity === 0 || yParity === 1) return yParity; if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0; throw new Error("Invalid `v` or `yParity` value"); })(); return `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; } // node_modules/viem/_esm/clients/createClient.js function createClient(parameters) { const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; const chain = parameters.chain; const account = parameters.account ? parseAccount(parameters.account) : void 0; const { config, request, value } = parameters.transport({ chain, pollingInterval }); const transport = { ...config, ...value }; const client = { account, batch, cacheTime, ccipRead, chain, key, name, pollingInterval, request, transport, type, uid: uid() }; function extend(base) { return (extendFn) => { const extended = extendFn(base); for (const key2 in client) delete extended[key2]; const combined = { ...base, ...extended }; return Object.assign(combined, { extend: extend(combined) }); }; } return Object.assign(client, { extend: extend(client) }); } // node_modules/viem/_esm/utils/ens/errors.js function isNullUniversalResolverError(err, callType) { if (!(err instanceof BaseError)) return false; const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); if (!(cause instanceof ContractFunctionRevertedError)) return false; if (cause.data?.errorName === "ResolverNotFound") return true; if (cause.data?.errorName === "ResolverWildcardNotSupported") return true; if (cause.data?.errorName === "ResolverNotContract") return true; if (cause.data?.errorName === "ResolverError") return true; if (cause.data?.errorName === "HttpError") return true; if (cause.reason?.includes("Wildcard on non-extended resolvers is not supported")) return true; if (callType === "reverse" && cause.reason === panicReasons[50]) return true; return false; } // node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js function encodedLabelToLabelhash(label) { if (label.length !== 66) return null; if (label.indexOf("[") !== 0) return null; if (label.indexOf("]") !== 65) return null; const hash = `0x${label.slice(1, 65)}`; if (!isHex(hash)) return null; return hash; } // node_modules/viem/_esm/utils/ens/namehash.js function namehash(name) { let result = new Uint8Array(32).fill(0); if (!name) return bytesToHex(result); const labels = name.split("."); for (let i = labels.length - 1; i >= 0; i -= 1) { const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); result = keccak256(concat([result, hashed]), "bytes"); } return bytesToHex(result); } // node_modules/viem/_esm/utils/ens/encodeLabelhash.js function encodeLabelhash(hash) { return `[${hash.slice(2)}]`; } // node_modules/viem/_esm/utils/ens/labelhash.js function labelhash(label) { const result = new Uint8Array(32).fill(0); if (!label) return bytesToHex(result); return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); } // node_modules/viem/_esm/utils/ens/packetToBytes.js function packetToBytes(packet) { const value = packet.replace(/^\.|\.$/gm, ""); if (value.length === 0) return new Uint8Array(1); const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); let offset = 0; const list = value.split("."); for (let i = 0; i < list.length; i++) { let encoded = stringToBytes(list[i]); if (encoded.byteLength > 255) encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); bytes[offset] = encoded.length; bytes.set(encoded, offset + 1); offset += encoded.length + 1; } if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1); return bytes; } // node_modules/viem/_esm/utils/getAction.js function getAction(client, actionFn, name) { const action_implicit = client[actionFn.name]; if (typeof action_implicit === "function") return action_implicit; const action_explicit = client[name]; if (typeof action_explicit === "function") return action_explicit; return (params) => actionFn(client, params); } // node_modules/viem/_esm/utils/errors/getContractError.js var EXECUTION_REVERTED_ERROR_CODE = 3; function getContractError(err, { abi: abi2, address, args, docsPath: docsPath3, functionName, sender }) { const { code, data, message, shortMessage } = err instanceof RawContractError ? err : err instanceof BaseError ? err.walk((err2) => "data" in err2) || err.walk() : {}; const cause = (() => { if (err instanceof AbiDecodingZeroDataError) return new ContractFunctionZeroDataError({ functionName }); if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || message || shortMessage)) { return new ContractFunctionRevertedError({ abi: abi2, data: typeof data === "object" ? data.data : data, functionName, message: shortMessage ?? message }); } return err; })(); return new ContractFunctionExecutionError(cause, { abi: abi2, args, contractAddress: address, docsPath: docsPath3, functionName, sender }); } // node_modules/viem/_esm/actions/public/readContract.js async function readContract(client, parameters) { const { abi: abi2, address, args, functionName, ...rest } = parameters; const calldata = encodeFunctionData({ abi: abi2, args, functionName }); try { const { data } = await getAction(client, call, "call")({ ...rest, data: calldata, to: address }); return decodeFunctionResult({ abi: abi2, args, functionName, data: data || "0x" }); } catch (error) { throw getContractError(error, { abi: abi2, address, args, docsPath: "/docs/contract/readContract", functionName }); } } // node_modules/viem/_esm/actions/ens/getEnsAddress.js async function getEnsAddress(client, { blockNumber, blockTag, coinType, name, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { let universalResolverAddress = universalResolverAddress_; if (!universalResolverAddress) { if (!client.chain) throw new Error("client chain not configured. universalResolverAddress is required."); universalResolverAddress = getChainContractAddress({ blockNumber, chain: client.chain, contract: "ensUniversalResolver" }); } try { const functionData = encodeFunctionData({ abi: addressResolverAbi, functionName: "addr", ...coinType != null ? { args: [namehash(name), BigInt(coinType)] } : { args: [namehash(name)] } }); const readContractParameters = { address: universalResolverAddress, abi: universalResolverResolveAbi, functionName: "resolve", args: [toHex(packetToBytes(name)), functionData], blockNumber, blockTag }; const readContractAction = getAction(client, readContract, "readContract"); const res = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] }) : await readContractAction(readContractParameters); if (res[0] === "0x") return null; const address = decodeFunctionResult({ abi: addressResolverAbi, args: coinType != null ? [namehash(name), BigInt(coinType)] : void 0, functionName: "addr", data: res[0] }); if (address === "0x") return null; if (trim(address) === "0x00") return null; return address; } catch (err) { if (strict) throw err; if (isNullUniversalResolverError(err, "resolve")) return null; throw err; } } // node_modules/viem/_esm/errors/ens.js var EnsAvatarInvalidMetadataError = class extends BaseError { constructor({ data }) { super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { metaMessages: [ "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", "", `Provided data: ${JSON.stringify(data)}` ] }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "EnsAvatarInvalidMetadataError" }); } }; var EnsAvatarInvalidNftUriError = class extends BaseError { constructor({ reason }) { super(`ENS NFT avatar URI is invalid. ${reason}`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "EnsAvatarInvalidNftUriError" }); } }; var EnsAvatarUriResolutionError = class extends BaseError { constructor({ uri }) { super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "EnsAvatarUriResolutionError" }); } }; var EnsAvatarUnsupportedNamespaceError = class extends BaseError { constructor({ namespace }) { super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "EnsAvatarUnsupportedNamespaceError" }); } }; // node_modules/viem/_esm/utils/ens/avatar/utils.js var networkRegex = /(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/; var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/; var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; async function isImageUri(uri) { try { const res = await fetch(uri, { method: "HEAD" }); if (res.status === 200) { const contentType = res.headers.get("content-type"); return contentType?.startsWith("image/"); } return false; } catch (error) { if (typeof error === "object" && typeof error.response !== "undefined") { return false; } if (!globalThis.hasOwnProperty("Image")) return false; return new Promise((resolve) => { const img = new Image(); img.onload = () => { resolve(true); }; img.onerror = () => { resolve(false); }; img.src = uri; }); } } function getGateway(custom, defaultGateway) { if (!custom) return defaultGateway; if (custom.endsWith("/")) return custom.slice(0, -1); return custom; } function resolveAvatarUri({ uri, gatewayUrls }) { const isEncoded = base64Regex.test(uri); if (isEncoded) return { uri, isOnChain: true, isEncoded }; const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); const networkRegexMatch = uri.match(networkRegex); const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); if (uri.startsWith("http") && !isIPNS && !isIPFS) { let replacedUri = uri; if (gatewayUrls?.arweave) replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); return { uri: replacedUri, isOnChain: false, isEncoded: false }; } if ((isIPNS || isIPFS) && target) { return { uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, isOnChain: false, isEncoded: false }; } if (protocol === "ar:/" && target) { return { uri: `${arweaveGateway}/${target}${subtarget || ""}`, isOnChain: false, isEncoded: false }; } let parsedUri = uri.replace(dataURIRegex, ""); if (parsedUri.startsWith("<svg")) { parsedUri = `data:image/svg+xml;base64,${btoa(parsedUri)}`; } if (parsedUri.startsWith("data:") || parsedUri.startsWith("{")) { return { uri: parsedUri, isOnChain: true, isEncoded: false }; } throw new EnsAvatarUriResolutionError({ uri }); } function getJsonImage(data) { if (typeof data !== "object" || !("image" in data) && !("image_url" in data) && !("image_data" in data)) { throw new EnsAvatarInvalidMetadataError({ data }); } return data.image || data.image_url || data.image_data; } async function getMetadataAvatarUri({ gatewayUrls, uri }) { try { const res = await fetch(uri).then((res2) => res2.json()); const image = await parseAvatarUri({ gatewayUrls, uri: getJsonImage(res) }); return image; } catch { throw new EnsAvatarUriResolutionError({ uri }); } } async function parseAvatarUri({ gatewayUrls, uri }) { const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); if (isOnChain) return resolvedURI; const isImage = await isImageUri(resolvedURI); if (isImage) return resolvedURI; throw new EnsAvatarUriResolutionError({ uri }); } function parseNftUri(uri_) { let uri = uri_; if (uri.startsWith("did:nft:")) { uri = uri.replace("did:nft:", "").replace(/_/g, "/"); } const [reference, asset_namespace, tokenID] = uri.split("/"); const [eip_namespace, chainID] = reference.split(":"); const [erc_namespace, contractAddress] = asset_namespace.split(":"); if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); if (!chainID) throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); if (!contractAddress) throw new EnsAvatarInvalidNftUriError({ reason: "Contract address not found" }); if (!tokenID) throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); if (!erc_namespace) throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); return { chainID: Number.parseInt(chainID), namespace: erc_namespace.toLowerCase(), contractAddress, tokenID }; } async function getNftTokenUri(client, { nft }) { if (nft.namespace === "erc721") { return readContract(client, { address: nft.contractAddress, abi: [ { name: "tokenURI", type: "function", stateMutability: "view", inputs: [{ name: "tokenId", type: "uint256" }], outputs: [{ name: "", type: "string" }] } ], functionName: "tokenURI", args: [BigInt(nft.tokenID)] }); } if (nft.namespace === "erc1155") { return readContract(client, { address: nft.contractAddress, abi: [ { name: "uri", type: "function", stateMutability: "view", inputs: [{ name: "_id", type: "uint256" }], outputs: [{ name: "", type: "string" }] } ], functionName: "uri", args: [BigInt(nft.tokenID)] }); } throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); } // node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js async function parseAvatarRecord(client, { gatewayUrls, record }) { if (/eip155:/i.test(record)) return parseNftAvatarUri(client, { gatewayUrls, record }); return parseAvatarUri({ uri: record, gatewayUrls }); } async function parseNftAvatarUri(client, { gatewayUrls, record }) { const nft = parseNftUri(record); const nftUri = await getNftTokenUri(client, { nft }); const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { const encodedJson = isEncoded ? ( // if it is encoded, decode it atob(resolvedNftUri.replace("data:application/json;base64,", "")) ) : ( // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) resolvedNftUri ); const decoded = JSON.parse(encodedJson); return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); } let uriTokenId = nft.tokenID; if (nft.namespace === "erc1155") uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); return getMetadataAvatarUri({ gatewayUrls, uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) }); } // node_modules/viem/_esm/actions/ens/getEnsText.js async function getEnsText(client, { blockNumber, blockTag, name, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { let universalResolverAddress = universalResolverAddress_; if (!universalResolverAddress) { if (!client.chain) throw new Error("client chain not configured. universalResolverAddress is required."); universalResolverAddress = getChainContractAddress({ blockNumber, chain: client.chain, contract: "ensUniversalResolver" }); } try { const readContractParameters = { address: universalResolverAddress, abi: universalResolverResolveAbi, functionName: "resolve", args: [ toHex(packetToBytes(name)), encodeFunctionData({ abi: textResolverAbi, functionName: "text", args: [namehash(name), key] }) ], blockNumber, blockTag }; const readContractAction = getAction(client, readContract, "readContract"); const res = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] }) : await readContractAction(readContractParameters); if (res[0] === "0x") return null; const record = decodeFunctionResult({ abi: textResolverAbi, functionName: "text", data: res[0] }); return record === "" ? null : record; } catch (err) { if (strict) throw err; if (isNullUniversalResolverError(err, "resolve")) return null; throw err; } } // node_modules/viem/_esm/actions/ens/getEnsAvatar.js async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { const record = await getAction(client, getEnsText, "getEnsText")({ blockNumber, blockTag, key: "avatar", name, universalResolverAddress, gatewayUrls, strict }); if (!record) return null; try { return await parseAvatarRecord(client, { record, gatewayUrls: assetGatewayUrls }); } catch { return null; } } // node_modules/viem/_esm/actions/ens/getEnsName.js async function getEnsName(client, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { let universalResolverAddress = universalResolverAddress_; if (!universalResolverAddress) { if (!client.chain) throw new Error("client chain not configured. universalResolverAddress is required."); universalResolverAddress = getChainContractAddress({ blockNumber, chain: client.chain, contract: "ensUniversalResolver" }); } const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; try { const readContractParameters = { address: universalResolverAddress, abi: universalResolverReverseAbi, functionName: "reverse", args: [toHex(packetToBytes(reverseNode))], blockNumber, blockTag }; const readContractAction = getAction(client, readContract, "readContract"); const [name, resolvedAddress] = gatewayUrls ? await readContractAction({ ...readContractParameters, args: [...readContractParameters.args, gatewayUrls] }) : await readContractAction(readContractParameters); if (address.toLowerCase() !== resolvedAddress.toLowerCase()) return null; return name; } catch (err) { if (strict) throw err; if (isNullUniversalResolverError(err, "reverse")) return null; throw err; } } // node_modules/viem/_esm/actions/ens/getEnsResolver.js async function getEnsResolver(client, { blockNumber, blockTag, name, universalResolverAddress: universalResolverAddress_ }) { let universalResolverAddress = universalResolverAddress_; if (!universalResolverAddress) { if (!client.chain) throw new Error("client chain not configured. universalResolverAddress is required."); universalResolverAddress = getChainContractAddress({ blockNumber, chain: client.chain, contract: "ensUniversalResolver" }); } const [resolverAddress] = await getAction(client, readContract, "readContract")({ address: universalResolverAddress, abi: [ { inputs: [{ type: "bytes" }], name: "findResolver", outputs: [{ type: "address" }, { type: "bytes32" }], stateMutability: "view", type: "function" } ], functionName: "findResolver", args: [toHex(packetToBytes(name))], blockNumber, blockTag }); return resolverAddress; } // node_modules/viem/_esm/utils/filters/createFilterRequestScope.js function createFilterRequestScope(client, { method }) { const requestMap = {}; if (client.transport.type === "fallback") client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => { if (status === "success" && method === method_) requestMap[id] = transport.request; }); return (id) => requestMap[id] || client.request; } // node_modules/viem/_esm/actions/public/createBlockFilter.js async function createBlockFilter(client) { const getRequest = createFilterRequestScope(client, { method: "eth_newBlockFilter" }); const id = await client.request({ method: "eth_newBlockFilter" }); return { id, request: getRequest(id), type: "block" }; } // node_modules/viem/_esm/errors/log.js var FilterTypeNotSupportedError = class extends BaseError { constructor(type) { super(`Filter type "${type}" is not supported.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "FilterTypeNotSupportedError" }); } }; // node_modules/viem/_esm/utils/abi/encodeEventTopics.js var docsPath = "/docs/contract/encodeEventTopics"; function encodeEventTopics(parameters) { const { abi: abi2, eventName, args } = parameters; let abiItem = abi2[0]; if (eventName) { const item = getAbiItem({ abi: abi2, name: eventName }); if (!item) throw new AbiEventNotFoundError(eventName, { docsPath }); abiItem = item; } if (abiItem.type !== "event") throw new AbiEventNotFoundError(void 0, { docsPath }); const definition = formatAbiItem(abiItem); const signature = toEventSelector(definition); let topics = []; if (args && "inputs" in abiItem) { const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed); const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : []; if (args_.length > 0) { topics = indexedInputs?.map((param, i) => { if (Array.isArray(args_[i])) return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] })); return args_[i] ? encodeArg({ param, value: args_[i] }) : null; }) ?? []; } } return [signature, ...topics]; } function encodeArg({ param, value }) { if (param.type === "string" || param.type === "bytes") return keccak256(toBytes(value)); if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) throw new FilterTypeNotSupportedError(param.type); return encodeAbiParameters([param], [value]); } // node_modules/viem/_esm/actions/public/createContractEventFilter.js async function createContractEventFilter(client, parameters) { const { address, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters; const getRequest = createFilterRequestScope(client, { method: "eth_newFilter" }); const topics = eventName ? encodeEventTopics({ abi: abi2, args, eventName }) : void 0; const id = await client.request({ method: "eth_newFilter", params: [ { address, fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, topics } ] }); return { abi: abi2, args, eventName, id, request: getRequest(id), strict: Boolean(strict), type: "event" }; } // node_modules/viem/_esm/actions/public/createEventFilter.js async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { const events = events_ ?? (event ? [event] : void 0); const getRequest = createFilterRequestScope(client, { method: "eth_newFilter" }); let topics = []; if (events) { const encoded = events.flatMap((event2) => encodeEventTopics({ abi: [event2], eventName: event2.name, args })); topics = [encoded]; if (event) topics = topics[0]; } const id = await client.request({ method: "eth_newFilter", params: [ { address, fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, ...topics.length ? { topics } : {} } ] }); return { abi: events, args, eventName: event ? event.name : void 0, fromBlock, id, request: getRequest(id), strict: Boolean(strict), toBlock, type: "event" }; } // node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js async function createPendingTransactionFilter(client) { const getRequest = createFilterRequestScope(client, { method: "eth_newPendingTransactionFilter" }); const id = await client.request({ method: "eth_newPendingTransactionFilter" }); return { id, request: getRequest(id), type: "transaction" }; } // node_modules/viem/_esm/errors/estimateGas.js var EstimateGasExecutionError = class extends BaseError { constructor(cause, { account, docsPath: docsPath3, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { const prettyArgs = prettyPrint({ from: account?.address, to, value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, data, gas, gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, nonce }); super(cause.shortMessage, { cause, docsPath: docsPath3, metaMessages: [ ...cause.metaMessages ? [...cause.metaMessages, " "] : [], "Estimate Gas Arguments:", prettyArgs ].filter(Boolean) }); Object.defineProperty(this, "cause", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "EstimateGasExecutionError" }); this.cause = cause; } }; // node_modules/viem/_esm/utils/errors/getEstimateGasError.js function getEstimateGasError(err, { docsPath: docsPath3, ...args }) { const cause = (() => { const cause2 = getNodeError(err, args); if (cause2 instanceof UnknownNodeError) return err; return cause2; })(); return new EstimateGasExecutionError(cause, { docsPath: docsPath3, ...args }); } // node_modules/viem/_esm/errors/fee.js var BaseFeeScalarError = class extends BaseError { constructor() { super("`baseFeeMultiplier` must be greater than 1."); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "BaseFeeScalarError" }); } }; var Eip1559FeesNotSupportedError = class extends BaseError { constructor() { super("Chain does not support EIP-1559 fees."); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "Eip1559FeesNotSupportedError" }); } }; var MaxFeePerGasTooLowError = class extends BaseError { constructor({ maxPriorityFeePerGas }) { super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "MaxFeePerGasTooLowError" }); } }; // node_modules/viem/_esm/errors/block.js var BlockNotFoundError = class extends BaseError { constructor({ blockHash, blockNumber }) { let identifier = "Block"; if (blockHash) identifier = `Block at hash "${blockHash}"`; if (blockNumber) identifier = `Block at number "${blockNumber}"`; super(`${identifier} could not be found.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "BlockNotFoundError" }); } }; // node_modules/viem/_esm/utils/formatters/transaction.js var transactionType = { "0x0": "legacy", "0x1": "eip2930", "0x2": "eip1559", "0x3": "eip4844" }; function formatTransaction(transaction) { const transaction_ = { ...transaction, blockHash: transaction.blockHash ? transaction.blockHash : null, blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null, chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0, gas: transaction.gas ? BigInt(transaction.gas) : void 0, gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0, maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0, maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0, maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0, nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0, to: transaction.to ? transaction.to : null, transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null, type: transaction.type ? transactionType[transaction.type] : void 0, typeHex: transaction.type ? transaction.type : void 0, value: transaction.value ? BigInt(transaction.value) : void 0, v: transaction.v ? BigInt(transaction.v) : void 0 }; transaction_.yParity = (() => { if (transaction.yParity) return Number(transaction.yParity); if (typeof transaction_.v === "bigint") { if (transaction_.v === 0n || transaction_.v === 27n) return 0; if (transaction_.v === 1n || transaction_.v === 28n) return 1; if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0; } return void 0; })(); if (transaction_.type === "legacy") { delete transaction_.accessList; delete transaction_.maxFeePerBlobGas; delete transaction_.maxFeePerGas; delete transaction_.maxPriorityFeePerGas; delete transaction_.yParity; } if (transaction_.type === "eip2930") { delete transaction_.maxFeePerBlobGas; delete transaction_.maxFeePerGas; delete transaction_.maxPriorityFeePerGas; } if (transaction_.type === "eip1559") { delete transaction_.maxFeePerBlobGas; } return transaction_; } var defineTransaction = /* @__PURE__ */ defineFormatter("transaction", formatTransaction); // node_modules/viem/_esm/utils/formatters/block.js function formatBlock(block) { const transactions = block.transactions?.map((transaction) => { if (typeof transaction === "string") return transaction; return formatTransaction(transaction); }); return { ...block, baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, gasLimit: block.gasLimit