From a7aa3eb9ff2c8f2fa544e0ecbbfdde0571339e55 Mon Sep 17 00:00:00 2001 From: mavisakalyan <55106546+mavisakalyan@users.noreply.github.com> Date: Thu, 2 Jan 2025 02:20:44 +0400 Subject: [PATCH 01/39] Initial commit --- README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..4109676 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# plugin-tee \ No newline at end of file From 16dd7e2344425268b386ddf7224c6b04ec166464 Mon Sep 17 00:00:00 2001 From: mavisakalyan <55106546+mavisakalyan@users.noreply.github.com> Date: Thu, 2 Jan 2025 02:43:11 +0400 Subject: [PATCH 02/39] Add files via upload --- README.md | 90 +++++- eslint.config.mjs | 3 + package.json | 26 ++ src/index.ts | 27 ++ src/providers/deriveKeyProvider.ts | 203 +++++++++++++ src/providers/remoteAttestationProvider.ts | 90 ++++++ src/providers/walletProvider.ts | 318 +++++++++++++++++++++ src/types/tee.ts | 11 + tsconfig.json | 10 + tsup.config.ts | 28 ++ 10 files changed, 805 insertions(+), 1 deletion(-) create mode 100644 eslint.config.mjs create mode 100644 package.json create mode 100644 src/index.ts create mode 100644 src/providers/deriveKeyProvider.ts create mode 100644 src/providers/remoteAttestationProvider.ts create mode 100644 src/providers/walletProvider.ts create mode 100644 src/types/tee.ts create mode 100644 tsconfig.json create mode 100644 tsup.config.ts diff --git a/README.md b/README.md index 4109676..c66bebf 100644 --- a/README.md +++ b/README.md @@ -1 +1,89 @@ -# plugin-tee \ No newline at end of file +# Plugin TEE + +A plugin for handling Trusted Execution Environment (TEE) operations. + +## Providers + +This plugin includes several providers for handling different TEE-related operations. + +### DeriveKeyProvider + +The `DeriveKeyProvider` allows for secure key derivation within a TEE environment. It supports deriving keys for both Solana (Ed25519) and Ethereum (ECDSA) chains. + +#### Usage + +```typescript +import { DeriveKeyProvider } from "@elizaos/plugin-tee"; + +// Initialize the provider +const provider = new DeriveKeyProvider(); + +// Derive a raw key +try { + const rawKey = await provider.rawDeriveKey( + "/path/to/derive", + "subject-identifier" + ); + // rawKey is a DeriveKeyResponse that can be used for further processing + // to get the uint8Array do the following + const rawKeyArray = rawKey.asUint8Array(); +} catch (error) { + console.error("Raw key derivation failed:", error); +} + +// Derive a Solana keypair (Ed25519) +try { + const solanaKeypair = await provider.deriveEd25519Keypair( + "/path/to/derive", + "subject-identifier" + ); + // solanaKeypair can now be used for Solana operations +} catch (error) { + console.error("Solana key derivation failed:", error); +} + +// Derive an Ethereum keypair (ECDSA) +try { + const evmKeypair = await provider.deriveEcdsaKeypair( + "/path/to/derive", + "subject-identifier" + ); + // evmKeypair can now be used for Ethereum operations +} catch (error) { + console.error("EVM key derivation failed:", error); +} +``` + +### RemoteAttestationProvider + +The `RemoteAttestationProvider` allows for generating a remote attestation within a TEE environment. + +#### Usage + +```typescript +const provider = new RemoteAttestationProvider(); + +try { + const attestation = await provider.generateAttestation("your-report-data"); + console.log("Attestation:", attestation); +} catch (error) { + console.error("Failed to generate attestation:", error); +} +``` + +### Configuration + +To get a TEE simulator for local testing, use the following commands: + +```bash +docker pull phalanetwork/tappd-simulator:latest +# by default the simulator is available in localhost:8090 +docker run --rm -p 8090:8090 phalanetwork/tappd-simulator:latest +``` + +When using the provider through the runtime environment, ensure the following settings are configured: + +```env +DSTACK_SIMULATOR_ENDPOINT="your-endpoint-url" # Optional, for simulator purposes if testing on mac or windows +WALLET_SECRET_SALT=your-secret-salt // Required to single agent deployments +``` diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..92fe5bb --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,3 @@ +import eslintGlobalConfig from "../../eslint.config.mjs"; + +export default [...eslintGlobalConfig]; diff --git a/package.json b/package.json new file mode 100644 index 0000000..837b010 --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "@elizaos/plugin-tee", + "version": "0.1.7-alpha.2", + "main": "src/index.ts", + "type": "module", + "dependencies": { + "@phala/dstack-sdk": "0.1.6", + "@solana/spl-token": "0.4.9", + "@solana/web3.js": "1.95.8", + "bignumber": "1.1.0", + "bignumber.js": "9.1.2", + "bs58": "6.0.0", + "node-cache": "5.1.2", + "pumpdotfun-sdk": "1.3.2", + "tsup": "8.3.5", + "viem": "2.21.53" + }, + "scripts": { + "build": "tsup --format esm --dts", + "dev": "tsup --format esm --dts --watch", + "lint": "eslint --fix --cache ." + }, + "peerDependencies": { + "whatwg-url": "7.1.0" + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..868078b --- /dev/null +++ b/src/index.ts @@ -0,0 +1,27 @@ +import { Plugin } from "@elizaos/core"; +import { remoteAttestationProvider } from "./providers/remoteAttestationProvider"; +import { deriveKeyProvider } from "./providers/deriveKeyProvider"; + +export { DeriveKeyProvider } from "./providers/deriveKeyProvider"; +export { RemoteAttestationProvider } from "./providers/remoteAttestationProvider"; +export { RemoteAttestationQuote, TEEMode } from "./types/tee"; + +export const teePlugin: Plugin = { + name: "tee", + description: + "TEE plugin with actions to generate remote attestations and derive keys", + actions: [ + /* custom actions */ + ], + evaluators: [ + /* custom evaluators */ + ], + providers: [ + /* custom providers */ + remoteAttestationProvider, + deriveKeyProvider, + ], + services: [ + /* custom services */ + ], +}; diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts new file mode 100644 index 0000000..c56dfa2 --- /dev/null +++ b/src/providers/deriveKeyProvider.ts @@ -0,0 +1,203 @@ +import { IAgentRuntime, Memory, Provider, State } from "@elizaos/core"; +import { Keypair } from "@solana/web3.js"; +import crypto from "crypto"; +import { DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; +import { privateKeyToAccount } from "viem/accounts"; +import { PrivateKeyAccount, keccak256 } from "viem"; +import { RemoteAttestationProvider } from "./remoteAttestationProvider"; +import { TEEMode, RemoteAttestationQuote } from "../types/tee"; + +interface DeriveKeyAttestationData { + agentId: string; + publicKey: string; +} + +class DeriveKeyProvider { + private client: TappdClient; + private raProvider: RemoteAttestationProvider; + + constructor(teeMode?: string) { + let endpoint: string | undefined; + + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = "http://localhost:8090"; + console.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case TEEMode.DOCKER: + endpoint = "http://host.docker.internal:8090"; + console.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + console.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + this.raProvider = new RemoteAttestationProvider(teeMode); + } + + private async generateDeriveKeyAttestation( + agentId: string, + publicKey: string + ): Promise { + const deriveKeyData: DeriveKeyAttestationData = { + agentId, + publicKey, + }; + const reportdata = JSON.stringify(deriveKeyData); + console.log("Generating Remote Attestation Quote for Derive Key..."); + const quote = await this.raProvider.generateAttestation(reportdata); + console.log("Remote Attestation Quote generated successfully!"); + return quote; + } + + async rawDeriveKey( + path: string, + subject: string + ): Promise { + try { + if (!path || !subject) { + console.error( + "Path and Subject are required for key derivation" + ); + } + + console.log("Deriving Raw Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + + console.log("Raw Key Derived Successfully!"); + return derivedKey; + } catch (error) { + console.error("Error deriving raw key:", error); + throw error; + } + } + + async deriveEd25519Keypair( + path: string, + subject: string, + agentId: string + ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { + try { + if (!path || !subject) { + console.error( + "Path and Subject are required for key derivation" + ); + } + + console.log("Deriving Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + const uint8ArrayDerivedKey = derivedKey.asUint8Array(); + + const hash = crypto.createHash("sha256"); + hash.update(uint8ArrayDerivedKey); + const seed = hash.digest(); + const seedArray = new Uint8Array(seed); + const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.publicKey.toBase58() + ); + console.log("Key Derived Successfully!"); + + return { keypair, attestation }; + } catch (error) { + console.error("Error deriving key:", error); + throw error; + } + } + + async deriveEcdsaKeypair( + path: string, + subject: string, + agentId: string + ): Promise<{ + keypair: PrivateKeyAccount; + attestation: RemoteAttestationQuote; + }> { + try { + if (!path || !subject) { + console.error( + "Path and Subject are required for key derivation" + ); + } + + console.log("Deriving ECDSA Key in TEE..."); + const deriveKeyResponse: DeriveKeyResponse = + await this.client.deriveKey(path, subject); + const hex = keccak256(deriveKeyResponse.asUint8Array()); + const keypair: PrivateKeyAccount = privateKeyToAccount(hex); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.address + ); + console.log("ECDSA Key Derived Successfully!"); + + return { keypair, attestation }; + } catch (error) { + console.error("Error deriving ecdsa key:", error); + throw error; + } + } +} + +const deriveKeyProvider: Provider = { + get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new DeriveKeyProvider(teeMode); + const agentId = runtime.agentId; + try { + // Validate wallet configuration + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + console.error( + "Wallet secret salt is not configured in settings" + ); + return ""; + } + + try { + const secretSalt = + runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; + const solanaKeypair = await provider.deriveEd25519Keypair( + "/", + secretSalt, + agentId + ); + const evmKeypair = await provider.deriveEcdsaKeypair( + "/", + secretSalt, + agentId + ); + return JSON.stringify({ + solana: solanaKeypair.keypair.publicKey, + evm: evmKeypair.keypair.address, + }); + } catch (error) { + console.error("Error creating PublicKey:", error); + return ""; + } + } catch (error) { + console.error("Error in derive key provider:", error.message); + return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`; + } + }, +}; + +export { deriveKeyProvider, DeriveKeyProvider }; diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts new file mode 100644 index 0000000..1e13c56 --- /dev/null +++ b/src/providers/remoteAttestationProvider.ts @@ -0,0 +1,90 @@ +import { IAgentRuntime, Memory, Provider, State } from "@elizaos/core"; +import { TdxQuoteResponse, TappdClient } from "@phala/dstack-sdk"; +import { RemoteAttestationQuote, TEEMode } from "../types/tee"; + +class RemoteAttestationProvider { + private client: TappdClient; + + constructor(teeMode?: string) { + let endpoint: string | undefined; + + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = "http://localhost:8090"; + console.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case TEEMode.DOCKER: + endpoint = "http://host.docker.internal:8090"; + console.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + console.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + } + + async generateAttestation( + reportData: string + ): Promise { + try { + console.log("Generating attestation for: ", reportData); + const tdxQuote: TdxQuoteResponse = + await this.client.tdxQuote(reportData); + const rtmrs = tdxQuote.replayRtmrs(); + console.log( + `rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f` + ); + const quote: RemoteAttestationQuote = { + quote: tdxQuote.quote, + timestamp: Date.now(), + }; + console.log("Remote attestation quote: ", quote); + return quote; + } catch (error) { + console.error("Error generating remote attestation:", error); + throw new Error( + `Failed to generate TDX Quote: ${ + error instanceof Error ? error.message : "Unknown error" + }` + ); + } + } +} + +// Keep the original provider for backwards compatibility +const remoteAttestationProvider: Provider = { + get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new RemoteAttestationProvider(teeMode); + const agentId = runtime.agentId; + + try { + console.log("Generating attestation for: ", agentId); + const attestation = await provider.generateAttestation(agentId); + return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; + } catch (error) { + console.error("Error in remote attestation provider:", error); + throw new Error( + `Failed to generate TDX Quote: ${ + error instanceof Error ? error.message : "Unknown error" + }` + ); + } + }, +}; + +export { remoteAttestationProvider, RemoteAttestationProvider }; diff --git a/src/providers/walletProvider.ts b/src/providers/walletProvider.ts new file mode 100644 index 0000000..b7111d0 --- /dev/null +++ b/src/providers/walletProvider.ts @@ -0,0 +1,318 @@ +/* This is an example of how WalletProvider can use DeriveKeyProvider to generate a Solana Keypair */ +import { IAgentRuntime, Memory, Provider, State } from "@elizaos/core"; +import { Connection, Keypair, PublicKey } from "@solana/web3.js"; +import BigNumber from "bignumber.js"; +import NodeCache from "node-cache"; +import { DeriveKeyProvider } from "./deriveKeyProvider"; +import { RemoteAttestationQuote } from "../types/tee"; +// Provider configuration +const PROVIDER_CONFIG = { + BIRDEYE_API: "https://public-api.birdeye.so", + MAX_RETRIES: 3, + RETRY_DELAY: 2000, + DEFAULT_RPC: "https://api.mainnet-beta.solana.com", + TOKEN_ADDRESSES: { + SOL: "So11111111111111111111111111111111111111112", + BTC: "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh", + ETH: "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs", + }, +}; + +export interface Item { + name: string; + address: string; + symbol: string; + decimals: number; + balance: string; + uiAmount: string; + priceUsd: string; + valueUsd: string; + valueSol?: string; +} + +interface WalletPortfolio { + totalUsd: string; + totalSol?: string; + items: Array; +} + +interface _BirdEyePriceData { + data: { + [key: string]: { + price: number; + priceChange24h: number; + }; + }; +} + +interface Prices { + solana: { usd: string }; + bitcoin: { usd: string }; + ethereum: { usd: string }; +} + +export class WalletProvider { + private cache: NodeCache; + + constructor( + private connection: Connection, + private walletPublicKey: PublicKey + ) { + this.cache = new NodeCache({ stdTTL: 300 }); // Cache TTL set to 5 minutes + } + + private async fetchWithRetry( + runtime, + url: string, + options: RequestInit = {} + ): Promise { + let lastError: Error; + + for (let i = 0; i < PROVIDER_CONFIG.MAX_RETRIES; i++) { + try { + const apiKey = runtime.getSetting("BIRDEYE_API_KEY"); + const response = await fetch(url, { + ...options, + headers: { + Accept: "application/json", + "x-chain": "solana", + "X-API-KEY": apiKey || "", + ...options.headers, + }, + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + `HTTP error! status: ${response.status}, message: ${errorText}` + ); + } + + const data = await response.json(); + return data; + } catch (error) { + console.error(`Attempt ${i + 1} failed:`, error); + lastError = error; + if (i < PROVIDER_CONFIG.MAX_RETRIES - 1) { + const delay = PROVIDER_CONFIG.RETRY_DELAY * Math.pow(2, i); + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + } + } + + console.error( + "All attempts failed. Throwing the last error:", + lastError + ); + throw lastError; + } + + async fetchPortfolioValue(runtime): Promise { + try { + const cacheKey = `portfolio-${this.walletPublicKey.toBase58()}`; + const cachedValue = this.cache.get(cacheKey); + + if (cachedValue) { + console.log("Cache hit for fetchPortfolioValue"); + return cachedValue; + } + console.log("Cache miss for fetchPortfolioValue"); + + const walletData = await this.fetchWithRetry( + runtime, + `${PROVIDER_CONFIG.BIRDEYE_API}/v1/wallet/token_list?wallet=${this.walletPublicKey.toBase58()}` + ); + + if (!walletData?.success || !walletData?.data) { + console.error("No portfolio data available", walletData); + throw new Error("No portfolio data available"); + } + + const data = walletData.data; + const totalUsd = new BigNumber(data.totalUsd.toString()); + const prices = await this.fetchPrices(runtime); + const solPriceInUSD = new BigNumber(prices.solana.usd.toString()); + + const items = data.items.map((item: any) => ({ + ...item, + valueSol: new BigNumber(item.valueUsd || 0) + .div(solPriceInUSD) + .toFixed(6), + name: item.name || "Unknown", + symbol: item.symbol || "Unknown", + priceUsd: item.priceUsd || "0", + valueUsd: item.valueUsd || "0", + })); + + const totalSol = totalUsd.div(solPriceInUSD); + const portfolio = { + totalUsd: totalUsd.toString(), + totalSol: totalSol.toFixed(6), + items: items.sort((a, b) => + new BigNumber(b.valueUsd) + .minus(new BigNumber(a.valueUsd)) + .toNumber() + ), + }; + this.cache.set(cacheKey, portfolio); + return portfolio; + } catch (error) { + console.error("Error fetching portfolio:", error); + throw error; + } + } + + async fetchPrices(runtime): Promise { + try { + const cacheKey = "prices"; + const cachedValue = this.cache.get(cacheKey); + + if (cachedValue) { + console.log("Cache hit for fetchPrices"); + return cachedValue; + } + console.log("Cache miss for fetchPrices"); + + const { SOL, BTC, ETH } = PROVIDER_CONFIG.TOKEN_ADDRESSES; + const tokens = [SOL, BTC, ETH]; + const prices: Prices = { + solana: { usd: "0" }, + bitcoin: { usd: "0" }, + ethereum: { usd: "0" }, + }; + + for (const token of tokens) { + const response = await this.fetchWithRetry( + runtime, + `${PROVIDER_CONFIG.BIRDEYE_API}/defi/price?address=${token}`, + { + headers: { + "x-chain": "solana", + }, + } + ); + + if (response?.data?.value) { + const price = response.data.value.toString(); + prices[ + token === SOL + ? "solana" + : token === BTC + ? "bitcoin" + : "ethereum" + ].usd = price; + } else { + console.warn(`No price data available for token: ${token}`); + } + } + + this.cache.set(cacheKey, prices); + return prices; + } catch (error) { + console.error("Error fetching prices:", error); + throw error; + } + } + + formatPortfolio( + runtime, + portfolio: WalletPortfolio, + prices: Prices + ): string { + let output = `${runtime.character.description}\n`; + output += `Wallet Address: ${this.walletPublicKey.toBase58()}\n\n`; + + const totalUsdFormatted = new BigNumber(portfolio.totalUsd).toFixed(2); + const totalSolFormatted = portfolio.totalSol; + + output += `Total Value: $${totalUsdFormatted} (${totalSolFormatted} SOL)\n\n`; + output += "Token Balances:\n"; + + const nonZeroItems = portfolio.items.filter((item) => + new BigNumber(item.uiAmount).isGreaterThan(0) + ); + + if (nonZeroItems.length === 0) { + output += "No tokens found with non-zero balance\n"; + } else { + for (const item of nonZeroItems) { + const valueUsd = new BigNumber(item.valueUsd).toFixed(2); + output += `${item.name} (${item.symbol}): ${new BigNumber( + item.uiAmount + ).toFixed(6)} ($${valueUsd} | ${item.valueSol} SOL)\n`; + } + } + + output += "\nMarket Prices:\n"; + output += `SOL: $${new BigNumber(prices.solana.usd).toFixed(2)}\n`; + output += `BTC: $${new BigNumber(prices.bitcoin.usd).toFixed(2)}\n`; + output += `ETH: $${new BigNumber(prices.ethereum.usd).toFixed(2)}\n`; + + return output; + } + + async getFormattedPortfolio(runtime): Promise { + try { + const [portfolio, prices] = await Promise.all([ + this.fetchPortfolioValue(runtime), + this.fetchPrices(runtime), + ]); + + return this.formatPortfolio(runtime, portfolio, prices); + } catch (error) { + console.error("Error generating portfolio report:", error); + return "Unable to fetch wallet information. Please try again later."; + } + } +} + +const walletProvider: Provider = { + get: async ( + runtime: IAgentRuntime, + _message: Memory, + _state?: State + ): Promise => { + const agentId = runtime.agentId; + const teeMode = runtime.getSetting("TEE_MODE"); + const deriveKeyProvider = new DeriveKeyProvider(teeMode); + try { + // Validate wallet configuration + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + console.error( + "Wallet secret salt is not configured in settings" + ); + return ""; + } + + let publicKey: PublicKey; + try { + const derivedKeyPair: { + keypair: Keypair; + attestation: RemoteAttestationQuote; + } = await deriveKeyProvider.deriveEd25519Keypair( + "/", + runtime.getSetting("WALLET_SECRET_SALT"), + agentId + ); + publicKey = derivedKeyPair.keypair.publicKey; + console.log("Wallet Public Key: ", publicKey.toBase58()); + } catch (error) { + console.error("Error creating PublicKey:", error); + return ""; + } + + const connection = new Connection(PROVIDER_CONFIG.DEFAULT_RPC); + const provider = new WalletProvider(connection, publicKey); + + const porfolio = await provider.getFormattedPortfolio(runtime); + return porfolio; + } catch (error) { + console.error("Error in wallet provider:", error.message); + return `Failed to fetch wallet information: ${error instanceof Error ? error.message : "Unknown error"}`; + } + }, +}; + +// Module exports +export { walletProvider }; diff --git a/src/types/tee.ts b/src/types/tee.ts new file mode 100644 index 0000000..8cdcae0 --- /dev/null +++ b/src/types/tee.ts @@ -0,0 +1,11 @@ +export enum TEEMode { + OFF = "OFF", + LOCAL = "LOCAL", // For local development with simulator + DOCKER = "DOCKER", // For docker development with simulator + PRODUCTION = "PRODUCTION" // For production without simulator +} + +export interface RemoteAttestationQuote { + quote: string; + timestamp: number; +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..73993de --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../core/tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": [ + "src/**/*.ts" + ] +} \ No newline at end of file diff --git a/tsup.config.ts b/tsup.config.ts new file mode 100644 index 0000000..b94c126 --- /dev/null +++ b/tsup.config.ts @@ -0,0 +1,28 @@ +import { defineConfig } from "tsup"; + +export default defineConfig({ + entry: ["src/index.ts"], + outDir: "dist", + sourcemap: true, + clean: true, + format: ["esm"], // Ensure you're targeting CommonJS + external: [ + "dotenv", // Externalize dotenv to prevent bundling + "fs", // Externalize fs to use Node.js built-in module + "path", // Externalize other built-ins if necessary + "@reflink/reflink", + "@node-llama-cpp", + "https", + "http", + "agentkeepalive", + // Add other modules you want to externalize + "@phala/dstack-sdk", + "safe-buffer", + "base-x", + "bs58", + "borsh", + "@solana/buffer-layout", + "stream", + "buffer", + ], +}); From 29c25548f6cb33bafaa5068445131ee3ec5b6574 Mon Sep 17 00:00:00 2001 From: mavisakalyan <55106546+mavisakalyan@users.noreply.github.com> Date: Thu, 2 Jan 2025 04:19:47 +0400 Subject: [PATCH 03/39] Update package.json --- package.json | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/package.json b/package.json index 837b010..f3238e4 100644 --- a/package.json +++ b/package.json @@ -22,5 +22,29 @@ }, "peerDependencies": { "whatwg-url": "7.1.0" + }, + "pluginType": "elizaos:plugin:1.0.0", + "pluginParameters": { + "type": "object", + "required": ["teeMode", "walletSecretSalt", "dstackSimulatorEndpoint"], + "properties": { + "teeMode": { + "type": "string", + "description": "Mode for TEE operation (LOCAL, DOCKER, PRODUCTION)" + }, + "walletSecretSalt": { + "type": "string", + "description": "Secret salt for wallet operations" + }, + "dstackSimulatorEndpoint": { + "type": "string", + "description": "Endpoint URL for TEE simulator (optional)" + } + } + }, + "pluginEnv": { + "TEE_MODE": "teeMode", + "WALLET_SECRET_SALT": "walletSecretSalt", + "DSTACK_SIMULATOR_ENDPOINT": "dstackSimulatorEndpoint" } } From 105bdf63797f0e12140c3d45ec32d673e05406b7 Mon Sep 17 00:00:00 2001 From: Avaer Kazmer Date: Tue, 14 Jan 2025 22:12:25 -0800 Subject: [PATCH 04/39] new source --- .npmignore | 6 + .turbo/turbo-build.log | 30 ++ README.md | 230 +++++++++++++++ eslint.config.mjs | 3 + package.json | 40 +++ src/actions/remoteAttestation.ts | 90 ++++++ src/index.ts | 29 ++ src/providers/deriveKeyProvider.ts | 211 +++++++++++++ src/providers/remoteAttestationProvider.ts | 97 ++++++ src/providers/walletProvider.ts | 326 +++++++++++++++++++++ src/types/tee.ts | 11 + tsconfig.json | 8 + tsup.config.ts | 29 ++ 13 files changed, 1110 insertions(+) create mode 100644 .npmignore create mode 100644 .turbo/turbo-build.log create mode 100644 README.md create mode 100644 eslint.config.mjs create mode 100644 package.json create mode 100644 src/actions/remoteAttestation.ts create mode 100644 src/index.ts create mode 100644 src/providers/deriveKeyProvider.ts create mode 100644 src/providers/remoteAttestationProvider.ts create mode 100644 src/providers/walletProvider.ts create mode 100644 src/types/tee.ts create mode 100644 tsconfig.json create mode 100644 tsup.config.ts diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..078562e --- /dev/null +++ b/.npmignore @@ -0,0 +1,6 @@ +* + +!dist/** +!package.json +!readme.md +!tsup.config.ts \ No newline at end of file diff --git a/.turbo/turbo-build.log b/.turbo/turbo-build.log new file mode 100644 index 0000000..665fb89 --- /dev/null +++ b/.turbo/turbo-build.log @@ -0,0 +1,30 @@ + + +> @elizaos/plugin-tee@0.1.8+build.1 build /Users/a/eliza-wrangler/packages/plugin-tee +> tsup --format esm --dts + +CLI Building entry: src/index.ts +CLI Using tsconfig: tsconfig.json +CLI tsup v8.3.5 +CLI Using tsup config: /Users/a/eliza-wrangler/packages/plugin-tee/tsup.config.ts +CLI Target: esnext +CLI Cleaning output folder +ESM Build start +ESM dist/secp256k1-QUTB2QC2.js 237.00 B +ESM dist/ccip-IAE5UWYX.js 290.00 B +ESM dist/chunk-4L6P6TY5.js 80.02 KB +ESM dist/chunk-KSHJJL6X.js 131.11 KB +ESM dist/index.js 49.07 KB +ESM dist/chunk-PR4QN5HX.js 1.87 KB +ESM dist/_esm-FVHF6KDD.js 130.62 KB +ESM dist/ccip-IAE5UWYX.js.map 71.00 B +ESM dist/secp256k1-QUTB2QC2.js.map 71.00 B +ESM dist/index.js.map 138.45 KB +ESM dist/chunk-4L6P6TY5.js.map 202.99 KB +ESM dist/_esm-FVHF6KDD.js.map 211.12 KB +ESM dist/chunk-KSHJJL6X.js.map 386.85 KB +ESM dist/chunk-PR4QN5HX.js.map 71.00 B +ESM ⚡️ Build success in 356ms +DTS Build start +DTS ⚡️ Build success in 5753ms +DTS dist/index.d.ts 1.37 KB diff --git a/README.md b/README.md new file mode 100644 index 0000000..358fa1e --- /dev/null +++ b/README.md @@ -0,0 +1,230 @@ +# @elizaos/plugin-tee + +A plugin for handling Trusted Execution Environment (TEE) operations, providing secure key derivation and remote attestation capabilities. + +## Overview + +This plugin provides functionality to: + +- Generate secure keys within a TEE environment +- Derive Ed25519 keypairs for Solana +- Derive ECDSA keypairs for Ethereum +- Generate remote attestation quotes +- Manage wallet interactions with TEE-derived keys + +## Installation + +```bash +npm install @elizaos/plugin-tee +``` + +## Configuration + +The plugin requires the following environment variables: + +```env +TEE_MODE=LOCAL|DOCKER|PRODUCTION +WALLET_SECRET_SALT=your_secret_salt # Required for single agent deployments +DSTACK_SIMULATOR_ENDPOINT=your-endpoint-url # Optional, for simulator purposes +``` + +## Usage + +Import and register the plugin in your Eliza configuration: + +```typescript +import { teePlugin } from "@elizaos/plugin-tee"; + +export default { + plugins: [teePlugin], + // ... other configuration +}; +``` + +## Features + +### DeriveKeyProvider + +The `DeriveKeyProvider` allows for secure key derivation within a TEE environment: + +```typescript +import { DeriveKeyProvider } from "@elizaos/plugin-tee"; + +// Initialize the provider +const provider = new DeriveKeyProvider(); + +// Derive a raw key +const rawKey = await provider.rawDeriveKey( + "/path/to/derive", + "subject-identifier" +); +// rawKey is a DeriveKeyResponse that can be used for further processing +const rawKeyArray = rawKey.asUint8Array(); + +// Derive a Solana keypair (Ed25519) +const solanaKeypair = await provider.deriveEd25519Keypair( + "/path/to/derive", + "subject-identifier" +); + +// Derive an Ethereum keypair (ECDSA) +const evmKeypair = await provider.deriveEcdsaKeypair( + "/path/to/derive", + "subject-identifier" +); +``` + +### RemoteAttestationProvider + +The `RemoteAttestationProvider` generates remote attestations within a TEE environment: + +```typescript +import { RemoteAttestationProvider } from "@elizaos/plugin-tee"; + +const provider = new RemoteAttestationProvider(); +const attestation = await provider.generateAttestation("your-report-data"); +``` + +## Development + +### Building + +```bash +npm run build +``` + +### Testing + +```bash +npm run test +``` + +## Local Development + +To get a TEE simulator for local testing, use the following commands: + +```bash +docker pull phalanetwork/tappd-simulator:latest +# by default the simulator is available in localhost:8090 +docker run --rm -p 8090:8090 phalanetwork/tappd-simulator:latest +``` + +## Dependencies + +- `@phala/dstack-sdk`: Core TEE functionality +- `@solana/web3.js`: Solana blockchain interaction +- `viem`: Ethereum interaction library +- Other standard dependencies listed in package.json + +## API Reference + +### Providers + +- `deriveKeyProvider`: Manages secure key derivation within TEE +- `remoteAttestationProvider`: Handles generation of remote attestation quotes +- `walletProvider`: Manages wallet interactions with TEE-derived keys + +### Types + +```typescript +enum TEEMode { + OFF = "OFF", + LOCAL = "LOCAL", // For local development with simulator + DOCKER = "DOCKER", // For docker development with simulator + PRODUCTION = "PRODUCTION", // For production without simulator +} + +interface RemoteAttestationQuote { + quote: string; + timestamp: number; +} +``` + +## Future Enhancements + +1. **Key Management** + + - Advanced key derivation schemes + - Multi-party computation support + - Key rotation automation + - Backup and recovery systems + - Hardware security module integration + - Custom derivation paths + +2. **Remote Attestation** + + - Enhanced quote verification + - Multiple TEE provider support + - Automated attestation renewal + - Policy management system + - Compliance reporting + - Audit trail generation + +3. **Security Features** + + - Memory encryption improvements + - Side-channel protection + - Secure state management + - Access control systems + - Threat detection + - Security monitoring + +4. **Chain Integration** + + - Multi-chain support expansion + - Cross-chain attestation + - Chain-specific optimizations + - Custom signing schemes + - Transaction privacy + - Bridge security + +5. **Developer Tools** + + - Enhanced debugging capabilities + - Testing framework + - Simulation environment + - Documentation generator + - Performance profiling + - Integration templates + +6. **Performance Optimization** + - Parallel processing + - Caching mechanisms + - Resource management + - Latency reduction + - Throughput improvements + - Load balancing + +We welcome community feedback and contributions to help prioritize these enhancements. + +## Contributing + +Contributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information. + +## Credits + +This plugin integrates with and builds upon several key technologies: + +- [Phala Network](https://phala.network/): Confidential smart contract platform +- [@phala/dstack-sdk](https://www.npmjs.com/package/@phala/dstack-sdk): Core TEE functionality +- [@solana/web3.js](https://www.npmjs.com/package/@solana/web3.js): Solana blockchain interaction +- [viem](https://www.npmjs.com/package/viem): Ethereum interaction library +- [Intel SGX](https://www.intel.com/content/www/us/en/developer/tools/software-guard-extensions/overview.html): Trusted Execution Environment technology + +Special thanks to: + +- The Phala Network team for their TEE infrastructure +- The Intel SGX team for TEE technology +- The dStack SDK maintainers +- The Eliza community for their contributions and feedback + +For more information about TEE capabilities: + +- [Phala Documentation](https://docs.phala.network/) +- [Intel SGX Documentation](https://www.intel.com/content/www/us/en/developer/tools/software-guard-extensions/documentation.html) +- [TEE Security Best Practices](https://docs.phala.network/developers/phat-contract/security-notes) +- [dStack SDK Reference](https://docs.phala.network/developers/dstack-sdk) + +## License + +This plugin is part of the Eliza project. See the main project repository for license information. diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..92fe5bb --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,3 @@ +import eslintGlobalConfig from "../../eslint.config.mjs"; + +export default [...eslintGlobalConfig]; diff --git a/package.json b/package.json new file mode 100644 index 0000000..58e2d94 --- /dev/null +++ b/package.json @@ -0,0 +1,40 @@ +{ + "name": "@elizaos/plugin-tee", + "version": "0.1.8+build.1", + "type": "module", + "main": "dist/index.js", + "module": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "@elizaos/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "dependencies": { + "@elizaos/core": "workspace:*", + "@phala/dstack-sdk": "0.1.7", + "@solana/spl-token": "0.4.9", + "@solana/web3.js": "1.95.8", + "bignumber.js": "9.1.2", + "bs58": "6.0.0", + "node-cache": "5.1.2", + "pumpdotfun-sdk": "1.3.2", + "tsup": "8.3.5" + }, + "scripts": { + "build": "tsup --format esm --dts", + "dev": "tsup --format esm --dts --watch", + "lint": "eslint --fix --cache ." + }, + "peerDependencies": { + "whatwg-url": "7.1.0" + } +} diff --git a/src/actions/remoteAttestation.ts b/src/actions/remoteAttestation.ts new file mode 100644 index 0000000..f1fddbd --- /dev/null +++ b/src/actions/remoteAttestation.ts @@ -0,0 +1,90 @@ +import type { IAgentRuntime, Memory, State, HandlerCallback } from "@elizaos/core"; +import { RemoteAttestationProvider } from "../providers/remoteAttestationProvider"; +import { fetch, type BodyInit } from "undici"; + +function hexToUint8Array(hex: string) { + hex = hex.trim(); + if (!hex) { + throw new Error("Invalid hex string"); + } + if (hex.startsWith("0x")) { + hex = hex.substring(2); + } + if (hex.length % 2 !== 0) { + throw new Error("Invalid hex string"); + } + + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + const byte = parseInt(hex.slice(i, i + 2), 16); + if (isNaN(byte)) { + throw new Error("Invalid hex string"); + } + array[i / 2] = byte; + } + return array; +} + +async function uploadUint8Array(data: Uint8Array) { + const blob = new Blob([data], { type: "application/octet-stream" }); + const formData = new FormData(); + formData.append("file", blob, 'quote.bin'); + + return await fetch("https://proof.t16z.com/api/upload", { + method: "POST", + body: formData as BodyInit, + }); +} + +export const remoteAttestationAction = { + name: "REMOTE_ATTESTATION", + similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"], + description: "Generate a remote attestation to prove that the agent is running in a TEE", + handler: async ( + runtime: IAgentRuntime, + _message: Memory, + _state: State, + _options: { [key: string]: unknown }, + callback: HandlerCallback, + ) => { + try { + // Get the remote attestation of the agentId + const agentId = runtime.agentId; + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new RemoteAttestationProvider(teeMode); + const attestation = await provider.generateAttestation(agentId, 'raw'); + const attestationData = hexToUint8Array(attestation.quote); + const response = await uploadUint8Array(attestationData); + const data = await response.json(); + callback({ + text: `Here's my 🧾 RA Quote 🫡 + https://proof.t16z.com/reports/${data.checksum}`, + action: "NONE", + }); + return true; + } catch (error) { + console.error("Failed to fetch remote attestation: ", error); + return false; + } + }, + validate: async (_runtime: IAgentRuntime) => { + return true; + }, + examples: [ + [ + { + user: "{{user1}}", + content: { + text: "If you are running in a TEE, generate a remote attestation", + }, + }, + { + user: "{{user2}}", + content: { + text: "Of course, one second...", + action: "REMOTE_ATTESTATION", + }, + } + ], + ], +}; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..4ebc26b --- /dev/null +++ b/src/index.ts @@ -0,0 +1,29 @@ +import { Plugin } from "@elizaos/core"; +import { remoteAttestationProvider } from "./providers/remoteAttestationProvider"; +import { deriveKeyProvider } from "./providers/deriveKeyProvider"; +import { remoteAttestationAction } from "./actions/remoteAttestation"; + +export { DeriveKeyProvider } from "./providers/deriveKeyProvider"; +export { RemoteAttestationProvider } from "./providers/remoteAttestationProvider"; +export { RemoteAttestationQuote, TEEMode } from "./types/tee"; + +export const teePlugin: Plugin = { + name: "tee", + description: + "TEE plugin with actions to generate remote attestations and derive keys", + actions: [ + /* custom actions */ + remoteAttestationAction, + ], + evaluators: [ + /* custom evaluators */ + ], + providers: [ + /* custom providers */ + remoteAttestationProvider, + deriveKeyProvider, + ], + services: [ + /* custom services */ + ], +}; diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts new file mode 100644 index 0000000..96430f2 --- /dev/null +++ b/src/providers/deriveKeyProvider.ts @@ -0,0 +1,211 @@ +import { + IAgentRuntime, + Memory, + Provider, + State, + elizaLogger, +} from "@elizaos/core"; +import { Keypair } from "@solana/web3.js"; +import crypto from "crypto"; +import { DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; +import { privateKeyToAccount } from "viem/accounts"; +import { PrivateKeyAccount, keccak256 } from "viem"; +import { RemoteAttestationProvider } from "./remoteAttestationProvider"; +import { TEEMode, RemoteAttestationQuote } from "../types/tee"; + +interface DeriveKeyAttestationData { + agentId: string; + publicKey: string; +} + +class DeriveKeyProvider { + private client: TappdClient; + private raProvider: RemoteAttestationProvider; + + constructor(teeMode?: string) { + let endpoint: string | undefined; + + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = "http://localhost:8090"; + elizaLogger.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case TEEMode.DOCKER: + endpoint = "http://host.docker.internal:8090"; + elizaLogger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + elizaLogger.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + this.raProvider = new RemoteAttestationProvider(teeMode); + } + + private async generateDeriveKeyAttestation( + agentId: string, + publicKey: string + ): Promise { + const deriveKeyData: DeriveKeyAttestationData = { + agentId, + publicKey, + }; + const reportdata = JSON.stringify(deriveKeyData); + elizaLogger.log( + "Generating Remote Attestation Quote for Derive Key..." + ); + const quote = await this.raProvider.generateAttestation(reportdata); + elizaLogger.log("Remote Attestation Quote generated successfully!"); + return quote; + } + + async rawDeriveKey( + path: string, + subject: string + ): Promise { + try { + if (!path || !subject) { + elizaLogger.error( + "Path and Subject are required for key derivation" + ); + } + + elizaLogger.log("Deriving Raw Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + + elizaLogger.log("Raw Key Derived Successfully!"); + return derivedKey; + } catch (error) { + elizaLogger.error("Error deriving raw key:", error); + throw error; + } + } + + async deriveEd25519Keypair( + path: string, + subject: string, + agentId: string + ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { + try { + if (!path || !subject) { + elizaLogger.error( + "Path and Subject are required for key derivation" + ); + } + + elizaLogger.log("Deriving Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + const uint8ArrayDerivedKey = derivedKey.asUint8Array(); + + const hash = crypto.createHash("sha256"); + hash.update(uint8ArrayDerivedKey); + const seed = hash.digest(); + const seedArray = new Uint8Array(seed); + const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.publicKey.toBase58() + ); + elizaLogger.log("Key Derived Successfully!"); + + return { keypair, attestation }; + } catch (error) { + elizaLogger.error("Error deriving key:", error); + throw error; + } + } + + async deriveEcdsaKeypair( + path: string, + subject: string, + agentId: string + ): Promise<{ + keypair: PrivateKeyAccount; + attestation: RemoteAttestationQuote; + }> { + try { + if (!path || !subject) { + elizaLogger.error( + "Path and Subject are required for key derivation" + ); + } + + elizaLogger.log("Deriving ECDSA Key in TEE..."); + const deriveKeyResponse: DeriveKeyResponse = + await this.client.deriveKey(path, subject); + const hex = keccak256(deriveKeyResponse.asUint8Array()); + const keypair: PrivateKeyAccount = privateKeyToAccount(hex); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.address + ); + elizaLogger.log("ECDSA Key Derived Successfully!"); + + return { keypair, attestation }; + } catch (error) { + elizaLogger.error("Error deriving ecdsa key:", error); + throw error; + } + } +} + +const deriveKeyProvider: Provider = { + get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new DeriveKeyProvider(teeMode); + const agentId = runtime.agentId; + try { + // Validate wallet configuration + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + elizaLogger.error( + "Wallet secret salt is not configured in settings" + ); + return ""; + } + + try { + const secretSalt = + runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; + const solanaKeypair = await provider.deriveEd25519Keypair( + "/", + secretSalt, + agentId + ); + const evmKeypair = await provider.deriveEcdsaKeypair( + "/", + secretSalt, + agentId + ); + return JSON.stringify({ + solana: solanaKeypair.keypair.publicKey, + evm: evmKeypair.keypair.address, + }); + } catch (error) { + elizaLogger.error("Error creating PublicKey:", error); + return ""; + } + } catch (error) { + elizaLogger.error("Error in derive key provider:", error.message); + return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`; + } + }, +}; + +export { deriveKeyProvider, DeriveKeyProvider }; diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts new file mode 100644 index 0000000..262b58c --- /dev/null +++ b/src/providers/remoteAttestationProvider.ts @@ -0,0 +1,97 @@ +import { + IAgentRuntime, + Memory, + Provider, + State, + elizaLogger, +} from "@elizaos/core"; +import { TdxQuoteResponse, TappdClient, TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; +import { RemoteAttestationQuote, TEEMode } from "../types/tee"; + +class RemoteAttestationProvider { + private client: TappdClient; + + constructor(teeMode?: string) { + let endpoint: string | undefined; + + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = "http://localhost:8090"; + elizaLogger.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case TEEMode.DOCKER: + endpoint = "http://host.docker.internal:8090"; + elizaLogger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + elizaLogger.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + } + + async generateAttestation( + reportData: string, + hashAlgorithm?: TdxQuoteHashAlgorithms + ): Promise { + try { + elizaLogger.log("Generating attestation for: ", reportData); + const tdxQuote: TdxQuoteResponse = + await this.client.tdxQuote(reportData, hashAlgorithm); + const rtmrs = tdxQuote.replayRtmrs(); + elizaLogger.log( + `rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f` + ); + const quote: RemoteAttestationQuote = { + quote: tdxQuote.quote, + timestamp: Date.now(), + }; + elizaLogger.log("Remote attestation quote: ", quote); + return quote; + } catch (error) { + console.error("Error generating remote attestation:", error); + throw new Error( + `Failed to generate TDX Quote: ${ + error instanceof Error ? error.message : "Unknown error" + }` + ); + } + } +} + +// Keep the original provider for backwards compatibility +const remoteAttestationProvider: Provider = { + get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new RemoteAttestationProvider(teeMode); + const agentId = runtime.agentId; + + try { + elizaLogger.log("Generating attestation for: ", agentId); + const attestation = await provider.generateAttestation(agentId, 'raw'); + return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; + } catch (error) { + console.error("Error in remote attestation provider:", error); + throw new Error( + `Failed to generate TDX Quote: ${ + error instanceof Error ? error.message : "Unknown error" + }` + ); + } + }, +}; + +export { remoteAttestationProvider, RemoteAttestationProvider }; diff --git a/src/providers/walletProvider.ts b/src/providers/walletProvider.ts new file mode 100644 index 0000000..a31cc65 --- /dev/null +++ b/src/providers/walletProvider.ts @@ -0,0 +1,326 @@ +/* This is an example of how WalletProvider can use DeriveKeyProvider to generate a Solana Keypair */ +import { + IAgentRuntime, + Memory, + Provider, + State, + elizaLogger, +} from "@elizaos/core"; +import { Connection, Keypair, PublicKey } from "@solana/web3.js"; +import BigNumber from "bignumber.js"; +import NodeCache from "node-cache"; +import { DeriveKeyProvider } from "./deriveKeyProvider"; +import { RemoteAttestationQuote } from "../types/tee"; +// Provider configuration +const PROVIDER_CONFIG = { + BIRDEYE_API: "https://public-api.birdeye.so", + MAX_RETRIES: 3, + RETRY_DELAY: 2000, + DEFAULT_RPC: "https://api.mainnet-beta.solana.com", + TOKEN_ADDRESSES: { + SOL: "So11111111111111111111111111111111111111112", + BTC: "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh", + ETH: "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs", + }, +}; + +export interface Item { + name: string; + address: string; + symbol: string; + decimals: number; + balance: string; + uiAmount: string; + priceUsd: string; + valueUsd: string; + valueSol?: string; +} + +interface WalletPortfolio { + totalUsd: string; + totalSol?: string; + items: Array; +} + +interface _BirdEyePriceData { + data: { + [key: string]: { + price: number; + priceChange24h: number; + }; + }; +} + +interface Prices { + solana: { usd: string }; + bitcoin: { usd: string }; + ethereum: { usd: string }; +} + +export class WalletProvider { + private cache: NodeCache; + + constructor( + private connection: Connection, + private walletPublicKey: PublicKey + ) { + this.cache = new NodeCache({ stdTTL: 300 }); // Cache TTL set to 5 minutes + } + + private async fetchWithRetry( + runtime, + url: string, + options: RequestInit = {} + ): Promise { + let lastError: Error; + + for (let i = 0; i < PROVIDER_CONFIG.MAX_RETRIES; i++) { + try { + const apiKey = runtime.getSetting("BIRDEYE_API_KEY"); + const response = await fetch(url, { + ...options, + headers: { + Accept: "application/json", + "x-chain": "solana", + "X-API-KEY": apiKey || "", + ...options.headers, + }, + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + `HTTP error! status: ${response.status}, message: ${errorText}` + ); + } + + const data = await response.json(); + return data; + } catch (error) { + elizaLogger.error(`Attempt ${i + 1} failed:`, error); + lastError = error; + if (i < PROVIDER_CONFIG.MAX_RETRIES - 1) { + const delay = PROVIDER_CONFIG.RETRY_DELAY * Math.pow(2, i); + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + } + } + + elizaLogger.error( + "All attempts failed. Throwing the last error:", + lastError + ); + throw lastError; + } + + async fetchPortfolioValue(runtime): Promise { + try { + const cacheKey = `portfolio-${this.walletPublicKey.toBase58()}`; + const cachedValue = this.cache.get(cacheKey); + + if (cachedValue) { + elizaLogger.log("Cache hit for fetchPortfolioValue"); + return cachedValue; + } + elizaLogger.log("Cache miss for fetchPortfolioValue"); + + const walletData = await this.fetchWithRetry( + runtime, + `${PROVIDER_CONFIG.BIRDEYE_API}/v1/wallet/token_list?wallet=${this.walletPublicKey.toBase58()}` + ); + + if (!walletData?.success || !walletData?.data) { + elizaLogger.error("No portfolio data available", walletData); + throw new Error("No portfolio data available"); + } + + const data = walletData.data; + const totalUsd = new BigNumber(data.totalUsd.toString()); + const prices = await this.fetchPrices(runtime); + const solPriceInUSD = new BigNumber(prices.solana.usd.toString()); + + const items = data.items.map((item: any) => ({ + ...item, + valueSol: new BigNumber(item.valueUsd || 0) + .div(solPriceInUSD) + .toFixed(6), + name: item.name || "Unknown", + symbol: item.symbol || "Unknown", + priceUsd: item.priceUsd || "0", + valueUsd: item.valueUsd || "0", + })); + + const totalSol = totalUsd.div(solPriceInUSD); + const portfolio = { + totalUsd: totalUsd.toString(), + totalSol: totalSol.toFixed(6), + items: items.sort((a, b) => + new BigNumber(b.valueUsd) + .minus(new BigNumber(a.valueUsd)) + .toNumber() + ), + }; + this.cache.set(cacheKey, portfolio); + return portfolio; + } catch (error) { + elizaLogger.error("Error fetching portfolio:", error); + throw error; + } + } + + async fetchPrices(runtime): Promise { + try { + const cacheKey = "prices"; + const cachedValue = this.cache.get(cacheKey); + + if (cachedValue) { + elizaLogger.log("Cache hit for fetchPrices"); + return cachedValue; + } + elizaLogger.log("Cache miss for fetchPrices"); + + const { SOL, BTC, ETH } = PROVIDER_CONFIG.TOKEN_ADDRESSES; + const tokens = [SOL, BTC, ETH]; + const prices: Prices = { + solana: { usd: "0" }, + bitcoin: { usd: "0" }, + ethereum: { usd: "0" }, + }; + + for (const token of tokens) { + const response = await this.fetchWithRetry( + runtime, + `${PROVIDER_CONFIG.BIRDEYE_API}/defi/price?address=${token}`, + { + headers: { + "x-chain": "solana", + }, + } + ); + + if (response?.data?.value) { + const price = response.data.value.toString(); + prices[ + token === SOL + ? "solana" + : token === BTC + ? "bitcoin" + : "ethereum" + ].usd = price; + } else { + elizaLogger.warn( + `No price data available for token: ${token}` + ); + } + } + + this.cache.set(cacheKey, prices); + return prices; + } catch (error) { + elizaLogger.error("Error fetching prices:", error); + throw error; + } + } + + formatPortfolio( + runtime, + portfolio: WalletPortfolio, + prices: Prices + ): string { + let output = `${runtime.character.description}\n`; + output += `Wallet Address: ${this.walletPublicKey.toBase58()}\n\n`; + + const totalUsdFormatted = new BigNumber(portfolio.totalUsd).toFixed(2); + const totalSolFormatted = portfolio.totalSol; + + output += `Total Value: $${totalUsdFormatted} (${totalSolFormatted} SOL)\n\n`; + output += "Token Balances:\n"; + + const nonZeroItems = portfolio.items.filter((item) => + new BigNumber(item.uiAmount).isGreaterThan(0) + ); + + if (nonZeroItems.length === 0) { + output += "No tokens found with non-zero balance\n"; + } else { + for (const item of nonZeroItems) { + const valueUsd = new BigNumber(item.valueUsd).toFixed(2); + output += `${item.name} (${item.symbol}): ${new BigNumber( + item.uiAmount + ).toFixed(6)} ($${valueUsd} | ${item.valueSol} SOL)\n`; + } + } + + output += "\nMarket Prices:\n"; + output += `SOL: $${new BigNumber(prices.solana.usd).toFixed(2)}\n`; + output += `BTC: $${new BigNumber(prices.bitcoin.usd).toFixed(2)}\n`; + output += `ETH: $${new BigNumber(prices.ethereum.usd).toFixed(2)}\n`; + + return output; + } + + async getFormattedPortfolio(runtime): Promise { + try { + const [portfolio, prices] = await Promise.all([ + this.fetchPortfolioValue(runtime), + this.fetchPrices(runtime), + ]); + + return this.formatPortfolio(runtime, portfolio, prices); + } catch (error) { + elizaLogger.error("Error generating portfolio report:", error); + return "Unable to fetch wallet information. Please try again later."; + } + } +} + +const walletProvider: Provider = { + get: async ( + runtime: IAgentRuntime, + _message: Memory, + _state?: State + ): Promise => { + const agentId = runtime.agentId; + const teeMode = runtime.getSetting("TEE_MODE"); + const deriveKeyProvider = new DeriveKeyProvider(teeMode); + try { + // Validate wallet configuration + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + elizaLogger.error( + "Wallet secret salt is not configured in settings" + ); + return ""; + } + + let publicKey: PublicKey; + try { + const derivedKeyPair: { + keypair: Keypair; + attestation: RemoteAttestationQuote; + } = await deriveKeyProvider.deriveEd25519Keypair( + "/", + runtime.getSetting("WALLET_SECRET_SALT"), + agentId + ); + publicKey = derivedKeyPair.keypair.publicKey; + elizaLogger.log("Wallet Public Key: ", publicKey.toBase58()); + } catch (error) { + elizaLogger.error("Error creating PublicKey:", error); + return ""; + } + + const connection = new Connection(PROVIDER_CONFIG.DEFAULT_RPC); + const provider = new WalletProvider(connection, publicKey); + + const porfolio = await provider.getFormattedPortfolio(runtime); + return porfolio; + } catch (error) { + elizaLogger.error("Error in wallet provider:", error.message); + return `Failed to fetch wallet information: ${error instanceof Error ? error.message : "Unknown error"}`; + } + }, +}; + +// Module exports +export { walletProvider }; diff --git a/src/types/tee.ts b/src/types/tee.ts new file mode 100644 index 0000000..de974c3 --- /dev/null +++ b/src/types/tee.ts @@ -0,0 +1,11 @@ +export enum TEEMode { + OFF = "OFF", + LOCAL = "LOCAL", // For local development with simulator + DOCKER = "DOCKER", // For docker development with simulator + PRODUCTION = "PRODUCTION", // For production without simulator +} + +export interface RemoteAttestationQuote { + quote: string; + timestamp: number; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..005fbac --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../core/tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"] +} diff --git a/tsup.config.ts b/tsup.config.ts new file mode 100644 index 0000000..153f665 --- /dev/null +++ b/tsup.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from "tsup"; + +export default defineConfig({ + entry: ["src/index.ts"], + outDir: "dist", + sourcemap: true, + clean: true, + format: ["esm"], // Ensure you're targeting CommonJS + external: [ + "dotenv", // Externalize dotenv to prevent bundling + "fs", // Externalize fs to use Node.js built-in module + "path", // Externalize other built-ins if necessary + "@reflink/reflink", + "@node-llama-cpp", + "https", + "http", + "agentkeepalive", + // Add other modules you want to externalize + "@phala/dstack-sdk", + "safe-buffer", + "base-x", + "bs58", + "borsh", + "@solana/buffer-layout", + "stream", + "buffer", + "undici", + ], +}); From c075c597389772ea126eed42cf4501a44ab1391d Mon Sep 17 00:00:00 2001 From: Avaer Kazmer Date: Wed, 15 Jan 2025 02:31:00 -0800 Subject: [PATCH 05/39] add dist --- dist/_esm-FVHF6KDD.js | 3913 +++++++++++++++++++++++++++++++ dist/_esm-FVHF6KDD.js.map | 1 + dist/ccip-IAE5UWYX.js | 14 + dist/ccip-IAE5UWYX.js.map | 1 + dist/chunk-4L6P6TY5.js | 2556 ++++++++++++++++++++ dist/chunk-4L6P6TY5.js.map | 1 + dist/chunk-KSHJJL6X.js | 4019 ++++++++++++++++++++++++++++++++ dist/chunk-KSHJJL6X.js.map | 1 + dist/chunk-PR4QN5HX.js | 43 + dist/chunk-PR4QN5HX.js.map | 1 + dist/index.d.ts | 41 + dist/index.js | 1603 +++++++++++++ dist/index.js.map | 1 + dist/secp256k1-QUTB2QC2.js | 14 + dist/secp256k1-QUTB2QC2.js.map | 1 + 15 files changed, 12210 insertions(+) create mode 100644 dist/_esm-FVHF6KDD.js create mode 100644 dist/_esm-FVHF6KDD.js.map create mode 100644 dist/ccip-IAE5UWYX.js create mode 100644 dist/ccip-IAE5UWYX.js.map create mode 100644 dist/chunk-4L6P6TY5.js create mode 100644 dist/chunk-4L6P6TY5.js.map create mode 100644 dist/chunk-KSHJJL6X.js create mode 100644 dist/chunk-KSHJJL6X.js.map create mode 100644 dist/chunk-PR4QN5HX.js create mode 100644 dist/chunk-PR4QN5HX.js.map create mode 100644 dist/index.d.ts create mode 100644 dist/index.js create mode 100644 dist/index.js.map create mode 100644 dist/secp256k1-QUTB2QC2.js create mode 100644 dist/secp256k1-QUTB2QC2.js.map diff --git a/dist/_esm-FVHF6KDD.js b/dist/_esm-FVHF6KDD.js new file mode 100644 index 0000000..d794ed1 --- /dev/null +++ b/dist/_esm-FVHF6KDD.js @@ -0,0 +1,3913 @@ +import { + __commonJS, + __export, + __require, + __toESM +} from "./chunk-PR4QN5HX.js"; + +// ../../node_modules/ws/lib/stream.js +var require_stream = __commonJS({ + "../../node_modules/ws/lib/stream.js"(exports, module) { + "use strict"; + var { Duplex } = __require("stream"); + function emitClose(stream) { + stream.emit("close"); + } + function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } + } + function duplexOnError(err) { + this.removeListener("error", duplexOnError); + this.destroy(); + if (this.listenerCount("error") === 0) { + this.emit("error", err); + } + } + function createWebSocketStream2(ws, options) { + let terminateOnDestroy = true; + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + ws.on("message", function message(msg, isBinary) { + const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + if (!duplex.push(data)) ws.pause(); + }); + ws.once("error", function error(err) { + if (duplex.destroyed) return; + terminateOnDestroy = false; + duplex.destroy(err); + }); + ws.once("close", function close() { + if (duplex.destroyed) return; + duplex.push(null); + }); + duplex._destroy = function(err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + let called = false; + ws.once("error", function error(err2) { + called = true; + callback(err2); + }); + ws.once("close", function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + if (terminateOnDestroy) ws.terminate(); + }; + duplex._final = function(callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._final(callback); + }); + return; + } + if (ws._socket === null) return; + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once("finish", function finish() { + callback(); + }); + ws.close(); + } + }; + duplex._read = function() { + if (ws.isPaused) ws.resume(); + }; + duplex._write = function(chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + ws.send(chunk, callback); + }; + duplex.on("end", duplexOnEnd); + duplex.on("error", duplexOnError); + return duplex; + } + module.exports = createWebSocketStream2; + } +}); + +// ../../node_modules/ws/lib/constants.js +var require_constants = __commonJS({ + "../../node_modules/ws/lib/constants.js"(exports, module) { + "use strict"; + var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; + var hasBlob = typeof Blob !== "undefined"; + if (hasBlob) BINARY_TYPES.push("blob"); + module.exports = { + BINARY_TYPES, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + hasBlob, + kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), + kListener: Symbol("kListener"), + kStatusCode: Symbol("status-code"), + kWebSocket: Symbol("websocket"), + NOOP: () => { + } + }; + } +}); + +// ../../node_modules/node-gyp-build/node-gyp-build.js +var require_node_gyp_build = __commonJS({ + "../../node_modules/node-gyp-build/node-gyp-build.js"(exports, module) { + var fs = __require("fs"); + var path = __require("path"); + var os = __require("os"); + var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; + var vars = process.config && process.config.variables || {}; + var prebuildsOnly = !!process.env.PREBUILDS_ONLY; + var abi = process.versions.modules; + var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; + var arch = process.env.npm_config_arch || os.arch(); + var platform = process.env.npm_config_platform || os.platform(); + var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc"); + var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; + var uv = (process.versions.uv || "").split(".")[0]; + module.exports = load; + function load(dir) { + return runtimeRequire(load.resolve(dir)); + } + load.resolve = load.path = function(dir) { + dir = path.resolve(dir || "."); + try { + var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_"); + if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"]; + } catch (err) { + } + if (!prebuildsOnly) { + var release = getFirst(path.join(dir, "build/Release"), matchBuild); + if (release) return release; + var debug = getFirst(path.join(dir, "build/Debug"), matchBuild); + if (debug) return debug; + } + var prebuild = resolve(dir); + if (prebuild) return prebuild; + var nearby = resolve(path.dirname(process.execPath)); + if (nearby) return nearby; + var target = [ + "platform=" + platform, + "arch=" + arch, + "runtime=" + runtime, + "abi=" + abi, + "uv=" + uv, + armv ? "armv=" + armv : "", + "libc=" + libc, + "node=" + process.versions.node, + process.versions.electron ? "electron=" + process.versions.electron : "", + typeof __webpack_require__ === "function" ? "webpack=true" : "" + // eslint-disable-line + ].filter(Boolean).join(" "); + throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n"); + function resolve(dir2) { + var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple); + var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]; + if (!tuple) return; + var prebuilds = path.join(dir2, "prebuilds", tuple.name); + var parsed = readdirSync(prebuilds).map(parseTags); + var candidates = parsed.filter(matchTags(runtime, abi)); + var winner = candidates.sort(compareTags(runtime))[0]; + if (winner) return path.join(prebuilds, winner.file); + } + }; + function readdirSync(dir) { + try { + return fs.readdirSync(dir); + } catch (err) { + return []; + } + } + function getFirst(dir, filter) { + var files = readdirSync(dir).filter(filter); + return files[0] && path.join(dir, files[0]); + } + function matchBuild(name) { + return /\.node$/.test(name); + } + function parseTuple(name) { + var arr = name.split("-"); + if (arr.length !== 2) return; + var platform2 = arr[0]; + var architectures = arr[1].split("+"); + if (!platform2) return; + if (!architectures.length) return; + if (!architectures.every(Boolean)) return; + return { name, platform: platform2, architectures }; + } + function matchTuple(platform2, arch2) { + return function(tuple) { + if (tuple == null) return false; + if (tuple.platform !== platform2) return false; + return tuple.architectures.includes(arch2); + }; + } + function compareTuples(a, b) { + return a.architectures.length - b.architectures.length; + } + function parseTags(file) { + var arr = file.split("."); + var extension = arr.pop(); + var tags = { file, specificity: 0 }; + if (extension !== "node") return; + for (var i = 0; i < arr.length; i++) { + var tag = arr[i]; + if (tag === "node" || tag === "electron" || tag === "node-webkit") { + tags.runtime = tag; + } else if (tag === "napi") { + tags.napi = true; + } else if (tag.slice(0, 3) === "abi") { + tags.abi = tag.slice(3); + } else if (tag.slice(0, 2) === "uv") { + tags.uv = tag.slice(2); + } else if (tag.slice(0, 4) === "armv") { + tags.armv = tag.slice(4); + } else if (tag === "glibc" || tag === "musl") { + tags.libc = tag; + } else { + continue; + } + tags.specificity++; + } + return tags; + } + function matchTags(runtime2, abi2) { + return function(tags) { + if (tags == null) return false; + if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false; + if (tags.abi && tags.abi !== abi2 && !tags.napi) return false; + if (tags.uv && tags.uv !== uv) return false; + if (tags.armv && tags.armv !== armv) return false; + if (tags.libc && tags.libc !== libc) return false; + return true; + }; + } + function runtimeAgnostic(tags) { + return tags.runtime === "node" && tags.napi; + } + function compareTags(runtime2) { + return function(a, b) { + if (a.runtime !== b.runtime) { + return a.runtime === runtime2 ? -1 : 1; + } else if (a.abi !== b.abi) { + return a.abi ? -1 : 1; + } else if (a.specificity !== b.specificity) { + return a.specificity > b.specificity ? -1 : 1; + } else { + return 0; + } + }; + } + function isNwjs() { + return !!(process.versions && process.versions.nw); + } + function isElectron() { + if (process.versions && process.versions.electron) return true; + if (process.env.ELECTRON_RUN_AS_NODE) return true; + return typeof window !== "undefined" && window.process && window.process.type === "renderer"; + } + function isAlpine(platform2) { + return platform2 === "linux" && fs.existsSync("/etc/alpine-release"); + } + load.parseTags = parseTags; + load.matchTags = matchTags; + load.compareTags = compareTags; + load.parseTuple = parseTuple; + load.matchTuple = matchTuple; + load.compareTuples = compareTuples; + } +}); + +// ../../node_modules/node-gyp-build/index.js +var require_node_gyp_build2 = __commonJS({ + "../../node_modules/node-gyp-build/index.js"(exports, module) { + var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; + if (typeof runtimeRequire.addon === "function") { + module.exports = runtimeRequire.addon.bind(runtimeRequire); + } else { + module.exports = require_node_gyp_build(); + } + } +}); + +// ../../node_modules/bufferutil/fallback.js +var require_fallback = __commonJS({ + "../../node_modules/bufferutil/fallback.js"(exports, module) { + "use strict"; + var mask = (source, mask2, output, offset, length) => { + for (var i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask2[i & 3]; + } + }; + var unmask = (buffer, mask2) => { + const length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] ^= mask2[i & 3]; + } + }; + module.exports = { mask, unmask }; + } +}); + +// ../../node_modules/bufferutil/index.js +var require_bufferutil = __commonJS({ + "../../node_modules/bufferutil/index.js"(exports, module) { + "use strict"; + try { + module.exports = require_node_gyp_build2()(__dirname); + } catch (e) { + module.exports = require_fallback(); + } + } +}); + +// ../../node_modules/ws/lib/buffer-util.js +var require_buffer_util = __commonJS({ + "../../node_modules/ws/lib/buffer-util.js"(exports, module) { + "use strict"; + var { EMPTY_BUFFER } = require_constants(); + var FastBuffer = Buffer[Symbol.species]; + function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + return target; + } + function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + } + function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } + } + function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); + } + function toBuffer(data) { + toBuffer.readOnly = true; + if (Buffer.isBuffer(data)) return data; + let buf; + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + return buf; + } + module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask + }; + if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require_bufferutil(); + module.exports.mask = function(source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + module.exports.unmask = function(buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + } + } + } +}); + +// ../../node_modules/ws/lib/limiter.js +var require_limiter = __commonJS({ + "../../node_modules/ws/lib/limiter.js"(exports, module) { + "use strict"; + var kDone = Symbol("kDone"); + var kRun = Symbol("kRun"); + var Limiter = class { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + if (this.jobs.length) { + const job = this.jobs.shift(); + this.pending++; + job(this[kDone]); + } + } + }; + module.exports = Limiter; + } +}); + +// ../../node_modules/ws/lib/permessage-deflate.js +var require_permessage_deflate = __commonJS({ + "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) { + "use strict"; + var zlib = __require("zlib"); + var bufferUtil = require_buffer_util(); + var Limiter = require_limiter(); + var { kStatusCode } = require_constants(); + var FastBuffer = Buffer[Symbol.species]; + var TRAILER = Buffer.from([0, 0, 255, 255]); + var kPerMessageDeflate = Symbol("permessage-deflate"); + var kTotalLength = Symbol("total-length"); + var kCallback = Symbol("callback"); + var kBuffers = Symbol("buffers"); + var kError = Symbol("error"); + var zlibLimiter; + var PerMessageDeflate = class { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + this.params = null; + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; + zlibLimiter = new Limiter(concurrency); + } + } + /** + * @type {String} + */ + static get extensionName() { + return "permessage-deflate"; + } + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + return params; + } + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); + return this.params; + } + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + if (this._deflate) { + const callback = this._deflate[kCallback]; + this._deflate.close(); + this._deflate = null; + if (callback) { + callback( + new Error( + "The deflate stream was closed while data was being processed" + ) + ); + } + } + } + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { + return false; + } + return true; + }); + if (!accepted) { + throw new Error("None of the extension offers can be accepted"); + } + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === "number") { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === "number") { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { + delete accepted.client_max_window_bits; + } + return accepted; + } + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === "number") { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + return params; + } + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + value = value[0]; + if (key === "client_max_window_bits") { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === "server_max_window_bits") { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + params[key] = value; + }); + }); + return configurations; + } + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? "client" : "server"; + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on("error", inflateOnError); + this._inflate.on("data", inflateOnData); + } + this._inflate[kCallback] = callback; + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + this._inflate.flush(() => { + const err = this._inflate[kError]; + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + const data2 = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + callback(null, data2); + }); + } + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? "server" : "client"; + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + this._deflate.on("data", deflateOnData); + } + this._deflate[kCallback] = callback; + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + return; + } + let data2 = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + if (fin) { + data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); + } + this._deflate[kCallback] = null; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + callback(null, data2); + }); + } + }; + module.exports = PerMessageDeflate; + function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; + } + function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { + this[kBuffers].push(chunk); + return; + } + this[kError] = new RangeError("Max payload size exceeded"); + this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; + this[kError][kStatusCode] = 1009; + this.removeListener("data", inflateOnData); + this.reset(); + } + function inflateOnError(err) { + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); + } + } +}); + +// ../../node_modules/ws/node_modules/utf-8-validate/fallback.js +var require_fallback2 = __commonJS({ + "../../node_modules/ws/node_modules/utf-8-validate/fallback.js"(exports, module) { + "use strict"; + function isValidUTF8(buf) { + const len = buf.length; + let i = 0; + while (i < len) { + if ((buf[i] & 128) === 0) { + i++; + } else if ((buf[i] & 224) === 192) { + if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { + return false; + } + i += 2; + } else if ((buf[i] & 240) === 224) { + if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // overlong + buf[i] === 237 && (buf[i + 1] & 224) === 160) { + return false; + } + i += 3; + } else if ((buf[i] & 248) === 240) { + if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // overlong + buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { + return false; + } + i += 4; + } else { + return false; + } + } + return true; + } + module.exports = isValidUTF8; + } +}); + +// ../../node_modules/ws/node_modules/utf-8-validate/index.js +var require_utf_8_validate = __commonJS({ + "../../node_modules/ws/node_modules/utf-8-validate/index.js"(exports, module) { + "use strict"; + try { + module.exports = require_node_gyp_build2()(__dirname); + } catch (e) { + module.exports = require_fallback2(); + } + } +}); + +// ../../node_modules/ws/lib/validation.js +var require_validation = __commonJS({ + "../../node_modules/ws/lib/validation.js"(exports, module) { + "use strict"; + var { isUtf8 } = __require("buffer"); + var { hasBlob } = require_constants(); + var tokenChars = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 0 - 15 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 16 - 31 + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + // 32 - 47 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + // 48 - 63 + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 64 - 79 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + // 80 - 95 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 96 - 111 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0 + // 112 - 127 + ]; + function isValidStatusCode(code) { + return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; + } + function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + while (i < len) { + if ((buf[i] & 128) === 0) { + i++; + } else if ((buf[i] & 224) === 192) { + if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { + return false; + } + i += 2; + } else if ((buf[i] & 240) === 224) { + if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong + buf[i] === 237 && (buf[i + 1] & 224) === 160) { + return false; + } + i += 3; + } else if ((buf[i] & 248) === 240) { + if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong + buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { + return false; + } + i += 4; + } else { + return false; + } + } + return true; + } + function isBlob(value) { + return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); + } + module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars + }; + if (isUtf8) { + module.exports.isValidUTF8 = function(buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; + } else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require_utf_8_validate(); + module.exports.isValidUTF8 = function(buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + } + } + } +}); + +// ../../node_modules/ws/lib/receiver.js +var require_receiver = __commonJS({ + "../../node_modules/ws/lib/receiver.js"(exports, module) { + "use strict"; + var { Writable } = __require("stream"); + var PerMessageDeflate = require_permessage_deflate(); + var { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket + } = require_constants(); + var { concat, toArrayBuffer, unmask } = require_buffer_util(); + var { isValidStatusCode, isValidUTF8 } = require_validation(); + var FastBuffer = Buffer[Symbol.species]; + var GET_INFO = 0; + var GET_PAYLOAD_LENGTH_16 = 1; + var GET_PAYLOAD_LENGTH_64 = 2; + var GET_MASK = 3; + var GET_DATA = 4; + var INFLATING = 5; + var DEFER_EVENT = 6; + var Receiver2 = class extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = void 0; + this._bufferedBytes = 0; + this._buffers = []; + this._compressed = false; + this._payloadLength = 0; + this._mask = void 0; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 8 && this._state == GET_INFO) return cb(); + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + if (n === this._buffers[0].length) return this._buffers.shift(); + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + const dst = Buffer.allocUnsafe(n); + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + n -= buf.length; + } while (n > 0); + return dst; + } + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + if (!this._errored) cb(); + } + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + const buf = this.consume(2); + if ((buf[0] & 48) !== 0) { + const error = this.createError( + RangeError, + "RSV2 and RSV3 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_2_3" + ); + cb(error); + return; + } + const compressed = (buf[0] & 64) === 64; + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error); + return; + } + this._fin = (buf[0] & 128) === 128; + this._opcode = buf[0] & 15; + this._payloadLength = buf[1] & 127; + if (this._opcode === 0) { + if (compressed) { + const error = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error); + return; + } + if (!this._fragmented) { + const error = this.createError( + RangeError, + "invalid opcode 0", + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error); + return; + } + this._opcode = this._fragmented; + } else if (this._opcode === 1 || this._opcode === 2) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error); + return; + } + this._compressed = compressed; + } else if (this._opcode > 7 && this._opcode < 11) { + if (!this._fin) { + const error = this.createError( + RangeError, + "FIN must be set", + true, + 1002, + "WS_ERR_EXPECTED_FIN" + ); + cb(error); + return; + } + if (compressed) { + const error = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error); + return; + } + if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" + ); + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error); + return; + } + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 128) === 128; + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + "MASK must be set", + true, + 1002, + "WS_ERR_EXPECTED_MASK" + ); + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + "MASK must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_MASK" + ); + cb(error); + return; + } + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + "Unsupported WebSocket frame: payload length > 2^53 - 1", + false, + 1009, + "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" + ); + cb(error); + return; + } + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 8) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ); + cb(error); + return; + } + } + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + this._mask = this.consume(4); + this._state = GET_DATA; + } + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + data = this.consume(this._payloadLength); + if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { + unmask(data, this._mask); + } + } + if (this._opcode > 7) { + this.controlMessage(data, cb); + return; + } + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + if (data.length) { + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + this.dataMessage(cb); + } + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ); + cb(error); + return; + } + this._fragments.push(buf); + } + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + const messageLength = this._messageLength; + const fragments = this._fragments; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + if (this._opcode === 2) { + let data; + if (this._binaryType === "nodebuffer") { + data = concat(fragments, messageLength); + } else if (this._binaryType === "arraybuffer") { + data = toArrayBuffer(concat(fragments, messageLength)); + } else if (this._binaryType === "blob") { + data = new Blob(fragments); + } else { + data = fragments; + } + if (this._allowSynchronousEvents) { + this.emit("message", data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + cb(error); + return; + } + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit("message", buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 8) { + if (data.length === 0) { + this._loop = false; + this.emit("conclude", 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + "WS_ERR_INVALID_CLOSE_CODE" + ); + cb(error); + return; + } + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + cb(error); + return; + } + this._loop = false; + this.emit("conclude", code, buf); + this.end(); + } + this._state = GET_INFO; + return; + } + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 9 ? "ping" : "pong", data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 9 ? "ping" : "pong", data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } + }; + module.exports = Receiver2; + } +}); + +// ../../node_modules/ws/lib/sender.js +var require_sender = __commonJS({ + "../../node_modules/ws/lib/sender.js"(exports, module) { + "use strict"; + var { Duplex } = __require("stream"); + var { randomFillSync } = __require("crypto"); + var PerMessageDeflate = require_permessage_deflate(); + var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants(); + var { isBlob, isValidStatusCode } = require_validation(); + var { mask: applyMask, toBuffer } = require_buffer_util(); + var kByteLength = Symbol("kByteLength"); + var maskBuffer = Buffer.alloc(4); + var RANDOM_POOL_SIZE = 8 * 1024; + var randomPool; + var randomPoolPointer = RANDOM_POOL_SIZE; + var DEFAULT = 0; + var DEFLATING = 1; + var GET_BLOB_DATA = 2; + var Sender2 = class _Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + this._socket = socket; + this._firstFragment = true; + this._compress = false; + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = void 0; + } + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + if (randomPool === void 0) { + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + let dataLength; + if (typeof data === "string") { + if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + let payloadLength = dataLength; + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + target[0] = options.fin ? options.opcode | 128 : options.opcode; + if (options.rsv1) target[0] |= 64; + target[1] = payloadLength; + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + if (!options.mask) return [target, data]; + target[1] |= 128; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + if (skipMasking) return [target, data]; + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + if (code === void 0) { + buf = EMPTY_BUFFER; + } else if (typeof code !== "number" || !isValidStatusCode(code)) { + throw new TypeError("First argument must be a valid error code number"); + } else if (data === void 0 || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + if (length > 123) { + throw new RangeError("The message must not be greater than 123 bytes"); + } + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + if (typeof data === "string") { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 8, + readOnly: false, + rsv1: false + }; + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(buf, options), cb); + } + } + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 9, + readOnly, + rsv1: false + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(data, options), cb); + } + } + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 10, + readOnly, + rsv1: false + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(data, options), cb); + } + } + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + if (options.fin) this._firstFragment = true; + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + blob.arrayBuffer().then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + "The socket was closed while the blob was being read" + ); + process.nextTick(callCallbacks, this, err, cb); + return; + } + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + if (!compress) { + this._state = DEFAULT; + this.sendFrame(_Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); + } + }).catch((err) => { + process.nextTick(onError, this, err, cb); + }); + } + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(_Sender.frame(data, options), cb); + return; + } + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + "The socket was closed while data was being compressed" + ); + callCallbacks(this, err, cb); + return; + } + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(_Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } + }; + module.exports = Sender2; + function callCallbacks(sender, err, cb) { + if (typeof cb === "function") cb(err); + for (let i = 0; i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + if (typeof callback === "function") callback(err); + } + } + function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); + } + } +}); + +// ../../node_modules/ws/lib/event-target.js +var require_event_target = __commonJS({ + "../../node_modules/ws/lib/event-target.js"(exports, module) { + "use strict"; + var { kForOnEventAttribute, kListener } = require_constants(); + var kCode = Symbol("kCode"); + var kData = Symbol("kData"); + var kError = Symbol("kError"); + var kMessage = Symbol("kMessage"); + var kReason = Symbol("kReason"); + var kTarget = Symbol("kTarget"); + var kType = Symbol("kType"); + var kWasClean = Symbol("kWasClean"); + var Event = class { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + /** + * @type {String} + */ + get type() { + return this[kType]; + } + }; + Object.defineProperty(Event.prototype, "target", { enumerable: true }); + Object.defineProperty(Event.prototype, "type", { enumerable: true }); + var CloseEvent = class extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + this[kCode] = options.code === void 0 ? 0 : options.code; + this[kReason] = options.reason === void 0 ? "" : options.reason; + this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; + } + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } + }; + Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); + var ErrorEvent = class extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + this[kError] = options.error === void 0 ? null : options.error; + this[kMessage] = options.message === void 0 ? "" : options.message; + } + /** + * @type {*} + */ + get error() { + return this[kError]; + } + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } + }; + Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); + Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); + var MessageEvent = class extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + this[kData] = options.data === void 0 ? null : options.data; + } + /** + * @type {*} + */ + get data() { + return this[kData]; + } + }; + Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); + var EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { + return; + } + } + let wrapper; + if (type === "message") { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent("message", { + data: isBinary ? data : data.toString() + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "close") { + wrapper = function onClose(code, message) { + const event = new CloseEvent("close", { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "error") { + wrapper = function onError(error) { + const event = new ErrorEvent("error", { + error, + message: error.message + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "open") { + wrapper = function onOpen() { + const event = new Event("open"); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } + }; + module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent + }; + function callListener(listener, thisArg, event) { + if (typeof listener === "object" && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } + } + } +}); + +// ../../node_modules/ws/lib/extension.js +var require_extension = __commonJS({ + "../../node_modules/ws/lib/extension.js"(exports, module) { + "use strict"; + var { tokenChars } = require_validation(); + function push(dest, name, elem) { + if (dest[name] === void 0) dest[name] = [elem]; + else dest[name].push(elem); + } + function parse(header) { + const offers = /* @__PURE__ */ Object.create(null); + let params = /* @__PURE__ */ Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + for (; i < header.length; i++) { + code = header.charCodeAt(i); + if (extensionName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 44) { + push(offers, name, params); + params = /* @__PURE__ */ Object.create(null); + } else { + extensionName = name; + } + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 32 || code === 9) { + if (end === -1 && start !== -1) end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + start = end = -1; + } else if (code === 61 && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 34 && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 92) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 34 && header.charCodeAt(i - 1) === 61) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 32 || code === 9)) { + if (end === -1) end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ""); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + paramName = void 0; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + if (start === -1 || inQuotes || code === 32 || code === 9) { + throw new SyntaxError("Unexpected end of input"); + } + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === void 0) { + push(offers, token, params); + } else { + if (paramName === void 0) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, "")); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + return offers; + } + function format(extensions) { + return Object.keys(extensions).map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations.map((params) => { + return [extension].concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); + }) + ).join("; "); + }).join(", "); + }).join(", "); + } + module.exports = { format, parse }; + } +}); + +// ../../node_modules/ws/lib/websocket.js +var require_websocket = __commonJS({ + "../../node_modules/ws/lib/websocket.js"(exports, module) { + "use strict"; + var EventEmitter = __require("events"); + var https = __require("https"); + var http = __require("http"); + var net = __require("net"); + var tls = __require("tls"); + var { randomBytes, createHash } = __require("crypto"); + var { Duplex, Readable } = __require("stream"); + var { URL } = __require("url"); + var PerMessageDeflate = require_permessage_deflate(); + var Receiver2 = require_receiver(); + var Sender2 = require_sender(); + var { isBlob } = require_validation(); + var { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP + } = require_constants(); + var { + EventTarget: { addEventListener, removeEventListener } + } = require_event_target(); + var { format, parse } = require_extension(); + var { toBuffer } = require_buffer_util(); + var closeTimeout = 30 * 1e3; + var kAborted = Symbol("kAborted"); + var protocolVersions = [8, 13]; + var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; + var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + var WebSocket4 = class _WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ""; + this._readyState = _WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + if (protocols === void 0) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === "object" && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._isServer = true; + } + } + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + this._binaryType = type; + if (this._receiver) this._receiver._binaryType = type; + } + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + return this._socket._writableState.length + this._sender._bufferedBytes; + } + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + /** + * @type {String} + */ + get url() { + return this._url; + } + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver2({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + const sender = new Sender2(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + receiver.on("conclude", receiverOnConclude); + receiver.on("drain", receiverOnDrain); + receiver.on("error", receiverOnError); + receiver.on("message", receiverOnMessage); + receiver.on("ping", receiverOnPing); + receiver.on("pong", receiverOnPong); + sender.onerror = senderOnError; + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + if (head.length > 0) socket.unshift(head); + socket.on("close", socketOnClose); + socket.on("data", socketOnData); + socket.on("end", socketOnEnd); + socket.on("error", socketOnError); + this._readyState = _WebSocket.OPEN; + this.emit("open"); + } + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = _WebSocket.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + return; + } + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + this._receiver.removeAllListeners(); + this._readyState = _WebSocket.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + } + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === _WebSocket.CLOSED) return; + if (this.readyState === _WebSocket.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; + } + if (this.readyState === _WebSocket.CLOSING) { + if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { + this._socket.end(); + } + return; + } + this._readyState = _WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + if (err) return; + this._closeFrameSent = true; + if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { + this._socket.end(); + } + }); + setCloseTimer(this); + } + /** + * Pause the socket. + * + * @public + */ + pause() { + if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { + return; + } + this._paused = true; + this._socket.pause(); + } + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data === "function") { + cb = data; + data = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data === "number") data = data.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + if (mask === void 0) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data === "function") { + cb = data; + data = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data === "number") data = data.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + if (mask === void 0) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + /** + * Resume the socket. + * + * @public + */ + resume() { + if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { + return; + } + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof options === "function") { + cb = options; + options = {}; + } + if (typeof data === "number") data = data.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + const opts = { + binary: typeof data !== "string", + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === _WebSocket.CLOSED) return; + if (this.readyState === _WebSocket.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; + } + if (this._socket) { + this._readyState = _WebSocket.CLOSING; + this._socket.destroy(); + } + } + }; + Object.defineProperty(WebSocket4, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket4.prototype, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket4, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket4.prototype, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket4, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket4.prototype, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket4, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + Object.defineProperty(WebSocket4.prototype, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + [ + "binaryType", + "bufferedAmount", + "extensions", + "isPaused", + "protocol", + "readyState", + "url" + ].forEach((property) => { + Object.defineProperty(WebSocket4.prototype, property, { enumerable: true }); + }); + ["open", "error", "close", "message"].forEach((method) => { + Object.defineProperty(WebSocket4.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + if (typeof handler !== "function") return; + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); + }); + WebSocket4.prototype.addEventListener = addEventListener; + WebSocket4.prototype.removeEventListener = removeEventListener; + module.exports = WebSocket4; + function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: void 0, + hostname: void 0, + protocol: void 0, + timeout: void 0, + method: "GET", + host: void 0, + path: void 0, + port: void 0 + }; + websocket._autoPong = opts.autoPong; + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` + ); + } + let parsedUrl; + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + if (parsedUrl.protocol === "http:") { + parsedUrl.protocol = "ws:"; + } else if (parsedUrl.protocol === "https:") { + parsedUrl.protocol = "wss:"; + } + websocket._url = parsedUrl.href; + const isSecure = parsedUrl.protocol === "wss:"; + const isIpcUrl = parsedUrl.protocol === "ws+unix:"; + let invalidUrlMessage; + if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { + invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = "The URL contains a fragment identifier"; + } + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString("base64"); + const request = isSecure ? https.request : http.request; + const protocolSet = /* @__PURE__ */ new Set(); + let perMessageDeflate; + opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + "Sec-WebSocket-Version": opts.protocolVersion, + "Sec-WebSocket-Key": key, + Connection: "Upgrade", + Upgrade: "websocket" + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers["Sec-WebSocket-Extensions"] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { + throw new SyntaxError( + "An invalid or duplicated subprotocol was specified" + ); + } + protocolSet.add(protocol); + } + opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers["Sec-WebSocket-Origin"] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + if (isIpcUrl) { + const parts = opts.path.split(":"); + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + let req; + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; + const headers = options && options.headers; + options = { ...options, headers: {} }; + if (headers) { + for (const [key2, value] of Object.entries(headers)) { + options.headers[key2.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount("redirect") === 0) { + const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; + if (!isSameHost || websocket._originalSecure && !isSecure) { + delete opts.headers.authorization; + delete opts.headers.cookie; + if (!isSameHost) delete opts.headers.host; + opts.auth = void 0; + } + } + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); + } + req = websocket._req = request(opts); + if (websocket._redirects) { + websocket.emit("redirect", websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + if (opts.timeout) { + req.on("timeout", () => { + abortHandshake(websocket, req, "Opening handshake has timed out"); + }); + } + req.on("error", (err) => { + if (req === null || req[kAborted]) return; + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + req.on("response", (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, "Maximum redirects exceeded"); + return; + } + req.abort(); + let addr; + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit("unexpected-response", req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + req.on("upgrade", (res, socket, head) => { + websocket.emit("upgrade", res); + if (websocket.readyState !== WebSocket4.CONNECTING) return; + req = websocket._req = null; + const upgrade = res.headers.upgrade; + if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { + abortHandshake(websocket, socket, "Invalid Upgrade header"); + return; + } + const digest = createHash("sha1").update(key + GUID).digest("base64"); + if (res.headers["sec-websocket-accept"] !== digest) { + abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); + return; + } + const serverProt = res.headers["sec-websocket-protocol"]; + let protError; + if (serverProt !== void 0) { + if (!protocolSet.size) { + protError = "Server sent a subprotocol but none was requested"; + } else if (!protocolSet.has(serverProt)) { + protError = "Server sent an invalid subprotocol"; + } + } else if (protocolSet.size) { + protError = "Server sent no subprotocol"; + } + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + if (serverProt) websocket._protocol = serverProt; + const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; + if (secWebSocketExtensions !== void 0) { + if (!perMessageDeflate) { + const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; + abortHandshake(websocket, socket, message); + return; + } + let extensions; + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + const extensionNames = Object.keys(extensions); + if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { + const message = "Server indicated an extension that was not requested"; + abortHandshake(websocket, socket, message); + return; + } + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } + } + function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket4.CLOSING; + websocket._errorEmitted = true; + websocket.emit("error", err); + websocket.emitClose(); + } + function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); + } + function tlsConnect(options) { + options.path = void 0; + if (!options.servername && options.servername !== "") { + options.servername = net.isIP(options.host) ? "" : options.host; + } + return tls.connect(options); + } + function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket4.CLOSING; + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + if (stream.socket && !stream.socket.destroyed) { + stream.socket.destroy(); + } + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once("error", websocket.emit.bind(websocket, "error")); + stream.once("close", websocket.emitClose.bind(websocket)); + } + } + function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } + } + function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + if (websocket._socket[kWebSocket] === void 0) return; + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + if (code === 1005) websocket.close(); + else websocket.close(code, reason); + } + function receiverOnDrain() { + const websocket = this[kWebSocket]; + if (!websocket.isPaused) websocket._socket.resume(); + } + function receiverOnError(err) { + const websocket = this[kWebSocket]; + if (websocket._socket[kWebSocket] !== void 0) { + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + websocket.close(err[kStatusCode]); + } + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); + } + } + function receiverOnFinish() { + this[kWebSocket].emitClose(); + } + function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit("message", data, isBinary); + } + function receiverOnPing(data) { + const websocket = this[kWebSocket]; + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit("ping", data); + } + function receiverOnPong(data) { + this[kWebSocket].emit("pong", data); + } + function resume(stream) { + stream.resume(); + } + function senderOnError(err) { + const websocket = this[kWebSocket]; + if (websocket.readyState === WebSocket4.CLOSED) return; + if (websocket.readyState === WebSocket4.OPEN) { + websocket._readyState = WebSocket4.CLOSING; + setCloseTimer(websocket); + } + this._socket.end(); + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); + } + } + function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + closeTimeout + ); + } + function socketOnClose() { + const websocket = this[kWebSocket]; + this.removeListener("close", socketOnClose); + this.removeListener("data", socketOnData); + this.removeListener("end", socketOnEnd); + websocket._readyState = WebSocket4.CLOSING; + let chunk; + if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { + websocket._receiver.write(chunk); + } + websocket._receiver.end(); + this[kWebSocket] = void 0; + clearTimeout(websocket._closeTimer); + if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { + websocket.emitClose(); + } else { + websocket._receiver.on("error", receiverOnFinish); + websocket._receiver.on("finish", receiverOnFinish); + } + } + function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } + } + function socketOnEnd() { + const websocket = this[kWebSocket]; + websocket._readyState = WebSocket4.CLOSING; + websocket._receiver.end(); + this.end(); + } + function socketOnError() { + const websocket = this[kWebSocket]; + this.removeListener("error", socketOnError); + this.on("error", NOOP); + if (websocket) { + websocket._readyState = WebSocket4.CLOSING; + this.destroy(); + } + } + } +}); + +// ../../node_modules/ws/lib/subprotocol.js +var require_subprotocol = __commonJS({ + "../../node_modules/ws/lib/subprotocol.js"(exports, module) { + "use strict"; + var { tokenChars } = require_validation(); + function parse(header) { + const protocols = /* @__PURE__ */ new Set(); + let start = -1; + let end = -1; + let i = 0; + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) end = i; + } else if (code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) end = i; + const protocol2 = header.slice(start, end); + if (protocols.has(protocol2)) { + throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); + } + protocols.add(protocol2); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + if (start === -1 || end !== -1) { + throw new SyntaxError("Unexpected end of input"); + } + const protocol = header.slice(start, i); + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + protocols.add(protocol); + return protocols; + } + module.exports = { parse }; + } +}); + +// ../../node_modules/ws/lib/websocket-server.js +var require_websocket_server = __commonJS({ + "../../node_modules/ws/lib/websocket-server.js"(exports, module) { + "use strict"; + var EventEmitter = __require("events"); + var http = __require("http"); + var { Duplex } = __require("stream"); + var { createHash } = __require("crypto"); + var extension = require_extension(); + var PerMessageDeflate = require_permessage_deflate(); + var subprotocol = require_subprotocol(); + var WebSocket4 = require_websocket(); + var { GUID, kWebSocket } = require_constants(); + var keyRegex = /^[+/0-9A-Za-z]{22}==$/; + var RUNNING = 0; + var CLOSING = 1; + var CLOSED = 2; + var WebSocketServer2 = class extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + options = { + allowSynchronousEvents: true, + autoPong: true, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, + // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket: WebSocket4, + ...options + }; + if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options must be specified' + ); + } + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + res.writeHead(426, { + "Content-Length": body.length, + "Content-Type": "text/plain" + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + if (this._server) { + const emitConnection = this.emit.bind(this, "connection"); + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, "listening"), + error: this.emit.bind(this, "error"), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = /* @__PURE__ */ new Set(); + this._shouldEmitClose = false; + } + this.options = options; + this._state = RUNNING; + } + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + if (!this._server) return null; + return this._server.address(); + } + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once("close", () => { + cb(new Error("The server is not running")); + }); + } + process.nextTick(emitClose, this); + return; + } + if (cb) this.once("close", cb); + if (this._state === CLOSING) return; + this._state = CLOSING; + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + this._removeListeners(); + this._removeListeners = this._server = null; + server.close(() => { + emitClose(this); + }); + } + } + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf("?"); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + if (pathname !== this.options.path) return false; + } + return true; + } + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on("error", socketOnError); + const key = req.headers["sec-websocket-key"]; + const upgrade = req.headers.upgrade; + const version = +req.headers["sec-websocket-version"]; + if (req.method !== "GET") { + const message = "Invalid HTTP method"; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { + const message = "Invalid Upgrade header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (key === void 0 || !keyRegex.test(key)) { + const message = "Missing or invalid Sec-WebSocket-Key header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (version !== 8 && version !== 13) { + const message = "Missing or invalid Sec-WebSocket-Version header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; + let protocols = /* @__PURE__ */ new Set(); + if (secWebSocketProtocol !== void 0) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = "Invalid Sec-WebSocket-Protocol header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; + const extensions = {}; + if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + try { + const offers = extension.parse(secWebSocketExtensions); + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + if (!socket.readable || !socket.writable) return socket.destroy(); + if (socket[kWebSocket]) { + throw new Error( + "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" + ); + } + if (this._state > RUNNING) return abortHandshake(socket, 503); + const digest = createHash("sha1").update(key + GUID).digest("base64"); + const headers = [ + "HTTP/1.1 101 Switching Protocols", + "Upgrade: websocket", + "Connection: Upgrade", + `Sec-WebSocket-Accept: ${digest}` + ]; + const ws = new this.options.WebSocket(null, void 0, this.options); + if (protocols.size) { + const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + this.emit("headers", headers, req); + socket.write(headers.concat("\r\n").join("\r\n")); + socket.removeListener("error", socketOnError); + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + if (this.clients) { + this.clients.add(ws); + ws.on("close", () => { + this.clients.delete(ws); + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + cb(ws, req); + } + }; + module.exports = WebSocketServer2; + function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; + } + function emitClose(server) { + server._state = CLOSED; + server.emit("close"); + } + function socketOnError() { + this.destroy(); + } + function abortHandshake(socket, code, message, headers) { + message = message || http.STATUS_CODES[code]; + headers = { + Connection: "close", + "Content-Type": "text/html", + "Content-Length": Buffer.byteLength(message), + ...headers + }; + socket.once("finish", socket.destroy); + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r +` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message + ); + } + function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount("wsClientError")) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + server.emit("wsClientError", err, socket, req); + } else { + abortHandshake(socket, code, message); + } + } + } +}); + +// ../../node_modules/ws/wrapper.mjs +var wrapper_exports = {}; +__export(wrapper_exports, { + Receiver: () => import_receiver.default, + Sender: () => import_sender.default, + WebSocket: () => import_websocket.default, + WebSocketServer: () => import_websocket_server.default, + createWebSocketStream: () => import_stream.default, + default: () => wrapper_default +}); +var import_stream = __toESM(require_stream(), 1); +var import_receiver = __toESM(require_receiver(), 1); +var import_sender = __toESM(require_sender(), 1); +var import_websocket = __toESM(require_websocket(), 1); +var import_websocket_server = __toESM(require_websocket_server(), 1); +var wrapper_default = import_websocket.default; + +// ../../node_modules/isows/_esm/utils.js +function getNativeWebSocket() { + if (typeof WebSocket !== "undefined") + return WebSocket; + if (typeof global.WebSocket !== "undefined") + return global.WebSocket; + if (typeof window.WebSocket !== "undefined") + return window.WebSocket; + if (typeof self.WebSocket !== "undefined") + return self.WebSocket; + throw new Error("`WebSocket` is not supported in this environment"); +} + +// ../../node_modules/isows/_esm/index.js +var WebSocket3 = (() => { + try { + return getNativeWebSocket(); + } catch { + if (import_websocket.default) + return import_websocket.default; + return wrapper_exports; + } +})(); +export { + WebSocket3 as WebSocket +}; +//# sourceMappingURL=_esm-FVHF6KDD.js.map \ No newline at end of file diff --git a/dist/_esm-FVHF6KDD.js.map b/dist/_esm-FVHF6KDD.js.map new file mode 100644 index 0000000..83ff82e --- /dev/null +++ b/dist/_esm-FVHF6KDD.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/ws/lib/stream.js","../../../node_modules/ws/lib/constants.js","../../../node_modules/node-gyp-build/node-gyp-build.js","../../../node_modules/node-gyp-build/index.js","../../../node_modules/bufferutil/fallback.js","../../../node_modules/bufferutil/index.js","../../../node_modules/ws/lib/buffer-util.js","../../../node_modules/ws/lib/limiter.js","../../../node_modules/ws/lib/permessage-deflate.js","../../../node_modules/ws/node_modules/utf-8-validate/fallback.js","../../../node_modules/ws/node_modules/utf-8-validate/index.js","../../../node_modules/ws/lib/validation.js","../../../node_modules/ws/lib/receiver.js","../../../node_modules/ws/lib/sender.js","../../../node_modules/ws/lib/event-target.js","../../../node_modules/ws/lib/extension.js","../../../node_modules/ws/lib/websocket.js","../../../node_modules/ws/lib/subprotocol.js","../../../node_modules/ws/lib/websocket-server.js","../../../node_modules/ws/wrapper.mjs","../../../node_modules/isows/utils.ts","../../../node_modules/isows/index.ts"],"sourcesContent":["'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/-\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of \n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","export function getNativeWebSocket() {\n if (typeof WebSocket !== \"undefined\") return WebSocket;\n if (typeof global.WebSocket !== \"undefined\") return global.WebSocket;\n if (typeof window.WebSocket !== \"undefined\") return window.WebSocket;\n if (typeof self.WebSocket !== \"undefined\") return self.WebSocket;\n throw new Error(\"`WebSocket` is not supported in this environment\");\n}\n","import * as WebSocket_ from \"ws\";\nimport { getNativeWebSocket } from \"./utils.js\";\n\nexport const WebSocket = (() => {\n try {\n return getNativeWebSocket();\n } catch {\n if (WebSocket_.WebSocket) return WebSocket_.WebSocket;\n return WebSocket_;\n }\n})();\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,EAAE,OAAO,IAAI,UAAQ,QAAQ;AAQnC,aAAS,UAAU,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GAAG;AAAA,MAC/C,OAAO;AACL,uBAAe,QAAQ,MAAM,OAAO;AAAA,MACtC;AAAA,IACF;AAAA;AAAA;;;AC3hBA;AAAA;AAAA,kCAAAC;AAAA,EAAA,4BAAAC;AAAA,EAAA,kCAAAC;AAAA,EAAA,+CAAAC;AAAA,EAAA,2CAAAC;AAAA,EAAA;AAAA;AAAA,oBAAkC;AAClC,sBAAqB;AACrB,oBAAmB;AACnB,uBAAsB;AACtB,8BAA4B;AAG5B,IAAO,kBAAQ,iBAAAC;;;ACPT,SAAU,qBAAkB;AAChC,MAAI,OAAO,cAAc;AAAa,WAAO;AAC7C,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,KAAK,cAAc;AAAa,WAAO,KAAK;AACvD,QAAM,IAAI,MAAM,kDAAkD;AACpE;;;ACHO,IAAMC,cAAa,MAAK;AAC7B,MAAI;AACF,WAAO,mBAAkB;EAC3B,QAAQ;AACN,QAAe,iBAAAA;AAAW,aAAkB,iBAAAA;AAC5C,WAAO;EACT;AACF,GAAE;","names":["createWebSocketStream","err","dir","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","Receiver","Sender","Receiver","Sender","WebSocket","key","protocol","WebSocket","WebSocketServer","Receiver","Sender","WebSocket","WebSocketServer","createWebSocketStream","WebSocket","WebSocket"]} \ No newline at end of file diff --git a/dist/ccip-IAE5UWYX.js b/dist/ccip-IAE5UWYX.js new file mode 100644 index 0000000..1893f40 --- /dev/null +++ b/dist/ccip-IAE5UWYX.js @@ -0,0 +1,14 @@ +import { + ccipRequest, + offchainLookup, + offchainLookupAbiItem, + offchainLookupSignature +} from "./chunk-KSHJJL6X.js"; +import "./chunk-PR4QN5HX.js"; +export { + ccipRequest, + offchainLookup, + offchainLookupAbiItem, + offchainLookupSignature +}; +//# sourceMappingURL=ccip-IAE5UWYX.js.map \ No newline at end of file diff --git a/dist/ccip-IAE5UWYX.js.map b/dist/ccip-IAE5UWYX.js.map new file mode 100644 index 0000000..84c51b2 --- /dev/null +++ b/dist/ccip-IAE5UWYX.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/dist/chunk-4L6P6TY5.js b/dist/chunk-4L6P6TY5.js new file mode 100644 index 0000000..973ee43 --- /dev/null +++ b/dist/chunk-4L6P6TY5.js @@ -0,0 +1,2556 @@ +import { + __export +} from "./chunk-PR4QN5HX.js"; + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js +function anumber(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + anumber(h.outputLen); + anumber(h.blockLen); +} +function aexists(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 aoutput(out, instance) { + abytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } +} + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js +import * as nc from "node:crypto"; +var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js +var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr = (word, shift) => word << 32 - shift | word >>> shift; +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + abytes(data); + return data; +} +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +var Hash = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === "function") { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + if (crypto && typeof crypto.randomBytes === "function") { + return crypto.randomBytes(bytesLength); + } + throw new Error("crypto.getRandomValues must be defined"); +} + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_md.js +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +var Chi = (a, b, c) => a & b ^ ~a & c; +var Maj = (a, b, c) => a & b ^ a & c ^ b & c; +var HashMD = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +}; + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js +var SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA256 = class extends HashMD { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + +// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js +var HMAC = class extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + ahash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + abytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js +var utils_exports = {}; +__export(utils_exports, { + aInRange: () => aInRange, + abool: () => abool, + abytes: () => abytes2, + bitGet: () => bitGet, + bitLen: () => bitLen, + bitMask: () => bitMask, + bitSet: () => bitSet, + bytesToHex: () => bytesToHex, + bytesToNumberBE: () => bytesToNumberBE, + bytesToNumberLE: () => bytesToNumberLE, + concatBytes: () => concatBytes2, + createHmacDrbg: () => createHmacDrbg, + ensureBytes: () => ensureBytes, + equalBytes: () => equalBytes, + hexToBytes: () => hexToBytes, + hexToNumber: () => hexToNumber, + inRange: () => inRange, + isBytes: () => isBytes2, + memoized: () => memoized, + notImplemented: () => notImplemented, + numberToBytesBE: () => numberToBytesBE, + numberToBytesLE: () => numberToBytesLE, + numberToHexUnpadded: () => numberToHexUnpadded, + numberToVarBytesBE: () => numberToVarBytesBE, + utf8ToBytes: () => utf8ToBytes2, + validateObject: () => validateObject +}); +var _0n = /* @__PURE__ */ BigInt(0); +var _1n = /* @__PURE__ */ BigInt(1); +var _2n = /* @__PURE__ */ BigInt(2); +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes2(item) { + if (!isBytes2(item)) + throw new Error("Uint8Array expected"); +} +function abool(title, value) { + if (typeof value !== "boolean") + throw new Error(title + " boolean expected, got " + value); +} +var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex(bytes) { + abytes2(bytes); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num2) { + const hex = num2.toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return hex === "" ? _0n : BigInt("0x" + hex); +} +var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error("hex string expected, got unpadded hex of length " + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + abytes2(bytes); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(title + " must be hex string or Uint8Array, cause: " + e); + } + } else if (isBytes2(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(title + " must be hex string or Uint8Array"); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(title + " of length " + expectedLength + " expected, got " + len); + return res; +} +function concatBytes2(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes2(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +var isPosBig = (n) => typeof n === "bigint" && _0n <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +function bitGet(n, pos) { + return n >> BigInt(pos) & _1n; +} +function bitSet(n, pos, value) { + return n | (value ? _1n : _0n) << BigInt(pos); +} +var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; +var u8n = (data) => new Uint8Array(data); +var u8fr = (arr) => Uint8Array.from(arr); +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n()) => { + k = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k = h(u8fr([1]), seed); + v = h(); + }; + const gen = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +var validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) +}; +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error("invalid validator function"); + const val = object[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object)) { + throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +var notImplemented = () => { + throw new Error("not implemented"); +}; +function memoized(fn) { + const map = /* @__PURE__ */ new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== void 0) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js +var _0n2 = BigInt(0); +var _1n2 = BigInt(1); +var _2n2 = /* @__PURE__ */ BigInt(2); +var _3n = /* @__PURE__ */ BigInt(3); +var _4n = /* @__PURE__ */ BigInt(4); +var _5n = /* @__PURE__ */ BigInt(5); +var _8n = /* @__PURE__ */ BigInt(8); +var _9n = /* @__PURE__ */ BigInt(9); +var _16n = /* @__PURE__ */ BigInt(16); +function mod(a, b) { + const result = a % b; + return result >= _0n2 ? result : b + result; +} +function pow(num2, power, modulo) { + if (power < _0n2) + throw new Error("invalid exponent, negatives unsupported"); + if (modulo <= _0n2) + throw new Error("invalid modulus"); + if (modulo === _1n2) + return _0n2; + let res = _1n2; + while (power > _0n2) { + if (power & _1n2) + res = res * num2 % modulo; + num2 = num2 * num2 % modulo; + power >>= _1n2; + } + return res; +} +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n2) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number, modulo) { + if (number === _0n2) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n2) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod(number, modulo); + let b = modulo; + let x = _0n2, y = _1n2, u = _1n2, v = _0n2; + while (a !== _0n2) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n2) + throw new Error("invert: does not exist"); + return mod(x, modulo); +} +function tonelliShanks(P) { + const legendreC = (P - _1n2) / _2n2; + let Q, S, Z; + for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) + ; + for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) { + if (Z > 1e3) + throw new Error("Cannot find square root: likely non-prime P"); + } + if (S === 1) { + const p1div4 = (P + _1n2) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n2) / _2n2; + return function tonelliSlow(Fp, n) { + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); + let x = Fp.pow(n, Q1div2); + let b = Fp.pow(n, Q); + while (!Fp.eql(b, Fp.ONE)) { + if (Fp.eql(b, Fp.ZERO)) + return Fp.ZERO; + let m = 1; + for (let t2 = Fp.sqr(b); m < r; m++) { + if (Fp.eql(t2, Fp.ONE)) + break; + t2 = Fp.sqr(t2); + } + const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1)); + g = Fp.sqr(ge); + x = Fp.mul(x, ge); + b = Fp.mul(b, g); + r = m; + } + return x; + }; +} +function FpSqrt(P) { + if (P % _4n === _3n) { + const p1div4 = (P + _1n2) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n2); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n2), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _16n === _9n) { + } + return tonelliShanks(P); +} +var FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f, num2, power) { + if (power < _0n2) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n2) + return f.ONE; + if (power === _1n2) + return num2; + let p = f.ONE; + let d = num2; + while (power > _0n2) { + if (power & _1n2) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n2; + } + return p; +} +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = acc; + return f.mul(acc, num2); + }, f.ONE); + const inverted = f.inv(lastMultiplied); + nums.reduceRight((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num2); + }, inverted); + return tmp; +} +function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field(ORDER, bitLen2, isLE = false, redef = {}) { + if (ORDER <= _0n2) + throw new Error("invalid field: expected ORDER > 0, got " + ORDER); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + let sqrtP; + const f = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n2, + ONE: _1n2, + create: (num2) => mod(num2, ORDER), + isValid: (num2) => { + if (typeof num2 !== "bigint") + throw new Error("invalid field element: expected bigint, got " + typeof num2); + return _0n2 <= num2 && num2 < ORDER; + }, + is0: (num2) => num2 === _0n2, + isOdd: (num2) => (num2 & _1n2) === _1n2, + neg: (num2) => mod(-num2, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num2) => mod(num2 * num2, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num2, power) => FpPow(f, num2, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num2) => num2 * num2, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num2) => invert(num2, ORDER), + sqrt: redef.sqrt || ((n) => { + if (!sqrtP) + sqrtP = FpSqrt(ORDER); + return sqrtP(f, n); + }), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => c ? b : a, + toBytes: (num2) => isLE ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + } + }); + return Object.freeze(f); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num2 = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + const reduced = mod(num2, fieldOrder - _1n2) + _1n2; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js +var _0n3 = BigInt(0); +var _1n3 = BigInt(1); +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function validateW(W, bits) { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); +} +function calcWOpts(W, bits) { + validateW(W, bits); + const windows = Math.ceil(bits / W) + 1; + const windowSize = 2 ** (W - 1); + return { windows, windowSize }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error("array expected"); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error("invalid point at index " + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error("array of scalars expected"); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error("invalid scalar at index " + i); + }); +} +var pointPrecomputes = /* @__PURE__ */ new WeakMap(); +var pointWindowSizes = /* @__PURE__ */ new WeakMap(); +function getW(P) { + return pointWindowSizes.get(P) || 1; +} +function wNAF(c, bits) { + return { + constTimeNegate, + hasPrecomputes(elm) { + return getW(elm) !== 1; + }, + // non-const time multiplication ladder + unsafeLadder(elm, n, p = c.ZERO) { + let d = elm; + while (n > _0n3) { + if (n & _1n3) + p = p.add(d); + d = d.double(); + n >>= _1n3; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param elm Point instance + * @param W window size + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = calcWOpts(W, bits); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + const { windows, windowSize } = calcWOpts(W, bits); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n3; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f }; + }, + /** + * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @param acc accumulator point to add result of multiplication + * @returns point + */ + wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { + const { windows, windowSize } = calcWOpts(W, bits); + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + if (n === _0n3) + break; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n3; + } + if (wbits === 0) + continue; + let curr = precomputes[offset + Math.abs(wbits) - 1]; + if (wbits < 0) + curr = curr.negate(); + acc = acc.add(curr); + } + return acc; + }, + getPrecomputes(W, P, transform) { + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return comp; + }, + wNAFCached(P, n, transform) { + const W = getW(P); + return this.wNAF(W, this.getPrecomputes(W, P, transform), n); + }, + wNAFCachedUnsafe(P, n, transform, prev) { + const W = getW(P); + if (W === 1) + return this.unsafeLadder(P, n, prev); + return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P, W) { + validateW(W, bits); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + } + }; +} +function pippenger(c, fieldN, points, scalars) { + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + if (points.length !== scalars.length) + throw new Error("arrays of points and scalars must have equal length"); + const zero = c.ZERO; + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(zero); + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j = 0; j < scalars.length; j++) { + const scalar = scalars[j]; + const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); + buckets[wbits2] = buckets[wbits2].add(points[j]); + } + let resI = zero; + for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js +function validateSigVerOpts(opts) { + if (opts.lowS !== void 0) + abool("lowS", opts.lowS); + if (opts.prehash !== void 0) + abool("prehash", opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function"); + } + } + return Object.freeze({ ...opts }); +} +var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; +var DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = "") { + super(m); + } + }, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b of lengthBytes) + length = length << 8 | b; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; + } + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num2) { + const { Err: E } = DER; + if (num2 < _0n4) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded(num2); + if (Number.parseInt(hex[0], 16) & 8) + hex = "00" + hex; + if (hex.length & 1) + throw new E("unexpected DER parsing assertion: unpadded hex"); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return b2n(data); + } + }, + toSig(hex) { + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === "string" ? h2b(hex) : hex; + abytes2(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); + if (seqLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); + if (sLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs = tlv.encode(2, int.encode(sig.r)); + const ss = tlv.encode(2, int.encode(sig.s)); + const seq = rs + ss; + return tlv.encode(48, seq); + } +}; +var _0n4 = BigInt(0); +var _1n4 = BigInt(1); +var _2n3 = BigInt(2); +var _3n2 = BigInt(3); +var _4n2 = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes2(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes) => { + const tail = bytes.subarray(1); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + }); + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); + const x3 = Fp.mul(x2, x); + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); + } + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num2) { + return inRange(num2, _1n4, CURVE.n); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== "bigint") { + if (isBytes2(key)) + key = bytesToHex(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("invalid private key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num2; + try { + num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); + } + if (wrapPrivateKey) + num2 = mod(num2, N); + aInRange("private key", num2, _1n4, N); + return num2; + } + function assertPrjPoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + if (p.is0()) { + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = p.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("bad point: x or y not FE"); + const left = Fp.sqr(y); + const right = weierstrassEquation(x); + if (!Fp.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!p.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + return true; + }); + class Point2 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp.isValid(pz)) + throw new Error("z required"); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + if (is0(x) && is0(y)) + return Point2.ZERO; + return new Point2(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex))); + P.assertValidity(); + return P; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point2, Fn, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point2(this.px, Fp.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + let t0 = Fp.mul(X1, X1); + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); + Z3 = Fp.add(Z3, Z3); + return new Point2(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n2); + let t0 = Fp.mul(X1, X2); + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); + return new Point2(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point2.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point2.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc) { + const { endo, n: N } = CURVE; + aInRange("scalar", sc, _0n4, N); + const I = Point2.ZERO; + if (sc === _0n4) + return I; + if (this.is0() || sc === _1n4) + return this; + if (!endo || wnaf.hasPrecomputes(this)) + return wnaf.wNAFCachedUnsafe(this, sc, Point2.normalizeZ); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n4 || k2 > _0n4) { + if (k1 & _1n4) + k1p = k1p.add(d); + if (k2 & _1n4) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n4; + k2 >>= _1n4; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N } = CURVE; + aInRange("scalar", scalar, _1n4, N); + let point, fake; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + return Point2.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G = Point2.BASE; + const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? void 0 : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n4) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n4) + return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool("isCompressed", isCompressed); + this.assertValidity(); + return toBytes2(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + abool("isCompressed", isCompressed); + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point2.ZERO = new Point2(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; + const uncompressedLen = 2 * Fp.BYTES + 1; + function modN2(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes2; + abool("isCompressed", isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); + } else { + return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n4, Fp.ORDER)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y; + try { + y = Fp.sqrt(y2); + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("Point is not on curve" + suffix); + } + const isYOdd = (y & _1n4) === _1n4; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + const cl = compressedLen; + const ul = uncompressedLen; + throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len); + } + } + }); + const numToNByteStr = (num2) => bytesToHex(numberToBytesBE(num2, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n4; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange("r", this.r, _1n4, CURVE_ORDER); + aInRange("s", this.s, _1n4, CURVE_ORDER); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point2.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN2(-h * ir); + const u2 = modN2(s * ir); + const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point2.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + } + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = isBytes2(item); + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b = Point2.fromHex(publicB); + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes) { + if (bytes.length > 8192) + throw new Error("input is too large"); + const num2 = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - CURVE.nBitLength; + return delta > 0 ? num2 >> BigInt(delta) : num2; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes) { + return modN2(bits2int(bytes)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num2) { + aInRange("num < 2^" + CURVE.nBitLength, num2, _0n4, ORDER_MASK); + return numberToBytesBE(num2, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k) => k in opts)) + throw new Error("sign() legacy options not supported"); + const { hash, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null && ent !== false) { + const e = ent === true ? randomBytes2(Fp.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); + } + const seed = concatBytes2(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) + return; + const ik = invN(k); + const q = Point2.BASE.multiply(k).toAffine(); + const r = modN2(q.x); + if (r === _0n4) + return; + const s = modN2(ik * modN2(m + r * d)); + if (s === _0n4) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point2.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + const { lowS, prehash, format } = opts; + validateSigVerOpts(opts); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + if (format !== void 0 && format !== "compact" && format !== "der") + throw new Error("format must be compact or der"); + const isHex = typeof sg === "string" || isBytes2(sg); + const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; + if (!isHex && !isObj) + throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); + let _sig = void 0; + let P; + try { + if (isObj) + _sig = new Signature(sg.r, sg.s); + if (isHex) { + try { + if (format !== "compact") + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + } + if (!_sig && format !== "der") + _sig = Signature.fromCompact(sg); + } + P = Point2.fromHex(publicKey); + } catch (error) { + return false; + } + if (!_sig) + return false; + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN2(h * is); + const u2 = modN2(r * is); + const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); + if (!R) + return false; + const v = modN2(R.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point2, + Signature, + utils + }; +} +function SWUFpSqrtRatio(Fp, Z) { + const q = Fp.ORDER; + let l = _0n4; + for (let o = q - _1n4; o % _2n3 === _0n4; o /= _2n3) + l += _1n4; + const c1 = l; + const _2n_pow_c1_1 = _2n3 << c1 - _1n4 - _1n4; + const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; + const c2 = (q - _1n4) / _2n_pow_c1; + const c3 = (c2 - _1n4) / _2n3; + const c4 = _2n_pow_c1 - _1n4; + const c5 = _2n_pow_c1_1; + const c6 = Fp.pow(Z, c2); + const c7 = Fp.pow(Z, (c2 + _1n4) / _2n3); + let sqrtRatio = (u, v) => { + let tv1 = c6; + let tv2 = Fp.pow(v, c4); + let tv3 = Fp.sqr(tv2); + tv3 = Fp.mul(tv3, v); + let tv5 = Fp.mul(u, tv3); + tv5 = Fp.pow(tv5, c3); + tv5 = Fp.mul(tv5, tv2); + tv2 = Fp.mul(tv5, v); + tv3 = Fp.mul(tv5, u); + let tv4 = Fp.mul(tv3, tv2); + tv5 = Fp.pow(tv4, c5); + let isQR = Fp.eql(tv5, Fp.ONE); + tv2 = Fp.mul(tv3, c7); + tv5 = Fp.mul(tv4, tv1); + tv3 = Fp.cmov(tv2, tv3, isQR); + tv4 = Fp.cmov(tv5, tv4, isQR); + for (let i = c1; i > _1n4; i--) { + let tv52 = i - _2n3; + tv52 = _2n3 << tv52 - _1n4; + let tvv5 = Fp.pow(tv4, tv52); + const e1 = Fp.eql(tvv5, Fp.ONE); + tv2 = Fp.mul(tv3, tv1); + tv1 = Fp.mul(tv1, tv1); + tvv5 = Fp.mul(tv4, tv1); + tv3 = Fp.cmov(tv2, tv3, e1); + tv4 = Fp.cmov(tvv5, tv4, e1); + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n2 === _3n2) { + const c12 = (Fp.ORDER - _3n2) / _4n2; + const c22 = Fp.sqrt(Fp.neg(Z)); + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); + const tv2 = Fp.mul(u, v); + tv1 = Fp.mul(tv1, tv2); + let y1 = Fp.pow(tv1, c12); + y1 = Fp.mul(y1, tv2); + const y2 = Fp.mul(y1, c22); + const tv3 = Fp.mul(Fp.sqr(y1), v); + const isQR = Fp.eql(tv3, u); + let y = Fp.cmov(y2, y1, isQR); + return { isValid: isQR, value: y }; + }; + } + return sqrtRatio; +} +function mapToCurveSimpleSWU(Fp, opts) { + validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error("mapToCurveSimpleSWU: invalid opts"); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error("Fp.isOdd is not implemented!"); + return (u) => { + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); + tv1 = Fp.mul(tv1, opts.Z); + tv2 = Fp.sqr(tv1); + tv2 = Fp.add(tv2, tv1); + tv3 = Fp.add(tv2, Fp.ONE); + tv3 = Fp.mul(tv3, opts.B); + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); + tv4 = Fp.mul(tv4, opts.A); + tv2 = Fp.sqr(tv3); + tv6 = Fp.sqr(tv4); + tv5 = Fp.mul(tv6, opts.A); + tv2 = Fp.add(tv2, tv5); + tv2 = Fp.mul(tv2, tv3); + tv6 = Fp.mul(tv6, tv4); + tv5 = Fp.mul(tv6, opts.B); + tv2 = Fp.add(tv2, tv5); + x = Fp.mul(tv1, tv3); + const { isValid, value } = sqrtRatio(tv2, tv6); + y = Fp.mul(tv1, u); + y = Fp.mul(y, value); + x = Fp.cmov(x, tv3, isValid); + y = Fp.cmov(y, value, isValid); + const e1 = Fp.isOdd(u) === Fp.isOdd(y); + y = Fp.cmov(Fp.neg(y), y, e1); + x = Fp.div(x, tv4); + return { x, y }; + }; +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js +function getHash(hash) { + return { + hash, + hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), + randomBytes + }; +} +function createCurve(curveDef, defHash) { + const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); + return Object.freeze({ ...create(defHash), create }); +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js +var os2ip = bytesToNumberBE; +function i2osp(value, length) { + anum(value); + anum(length); + if (value < 0 || value >= 1 << 8 * length) + throw new Error("invalid I2OSP input: " + value); + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 255; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function anum(item) { + if (!Number.isSafeInteger(item)) + throw new Error("number expected"); +} +function expand_message_xmd(msg, DST, lenInBytes, H) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) + DST = H(concatBytes2(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) + throw new Error("expand_message_xmd: invalid lenInBytes"); + const DST_prime = concatBytes2(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); + const b = new Array(ell); + const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes2(...args)); + } + const pseudo_random_bytes = concatBytes2(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +function expand_message_xof(msg, DST, lenInBytes, k, H) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) { + const dkLen = Math.ceil(2 * k / 8); + DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error("expand_message_xof: invalid lenInBytes"); + return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); +} +function hash_to_field(msg, count, options) { + validateObject(options, { + DST: "stringOrUint8Array", + p: "bigint", + m: "isSafeInteger", + k: "isSafeInteger", + hash: "hash" + }); + const { p, k, m, hash, expand, DST: _DST } = options; + abytes2(msg); + anum(count); + const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); + const len_in_bytes = count * m * L; + let prb; + if (expand === "xmd") { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } else if (expand === "xof") { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } else if (expand === "_internal_pass") { + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +function isogenyMap(field, map) { + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); + y = field.mul(y, field.div(yNum, yDen)); + return { x, y }; + }; +} +function createHasher(Point2, mapToCurve, def) { + if (typeof mapToCurve !== "function") + throw new Error("mapToCurve() must be defined"); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point2.fromAffine(mapToCurve(u[0])); + const u1 = Point2.fromAffine(mapToCurve(u[1])); + const P = u0.add(u1).clearCofactor(); + P.assertValidity(); + return P; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); + P.assertValidity(); + return P; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error("mapToCurve: expected array of bigints"); + for (const i of scalars) + if (typeof i !== "bigint") + throw new Error("mapToCurve: expected array of bigints"); + const P = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); + P.assertValidity(); + return P; + } + }; +} + +// ../../node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js +var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); +var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +var _1n5 = BigInt(1); +var _2n4 = BigInt(2); +var divNearest = (a, b) => (a + b / _2n4) / b; +function sqrtMod(y) { + const P = secp256k1P; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y * y * y % P; + const b3 = b2 * b2 * y % P; + const b6 = pow2(b3, _3n3, P) * b3 % P; + const b9 = pow2(b6, _3n3, P) * b3 % P; + const b11 = pow2(b9, _2n4, P) * b2 % P; + const b22 = pow2(b11, _11n, P) * b11 % P; + const b44 = pow2(b22, _22n, P) * b22 % P; + const b88 = pow2(b44, _44n, P) * b44 % P; + const b176 = pow2(b88, _88n, P) * b88 % P; + const b220 = pow2(b176, _44n, P) * b44 % P; + const b223 = pow2(b220, _3n3, P) * b3 % P; + const t1 = pow2(b223, _23n, P) * b22 % P; + const t2 = pow2(t1, _6n, P) * b2 % P; + const root = pow2(t2, _2n4, P); + if (!Fpk1.eql(Fpk1.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; +} +var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); +var secp256k1 = createCurve({ + a: BigInt(0), + // equation params: a, b + b: BigInt(7), + // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 + Fp: Fpk1, + // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, + // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + // Cofactor + lowS: true, + // Allow only low-S signatures by default in sign() and verify() + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + } + } +}, sha256); +var _0n5 = BigInt(0); +var TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes2(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes2(tagP, ...messages)); +} +var pointToBytes = (point) => point.toRawBytes(true).slice(1); +var numTo32b = (n) => numberToBytesBE(n, 32); +var modP = (x) => mod(x, secp256k1P); +var modN = (x) => mod(x, secp256k1N); +var Point = secp256k1.ProjectivePoint; +var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; +} +function lift_x(x) { + aInRange("x", x, _1n5, secp256k1P); + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); + let y = sqrtMod(c); + if (y % _2n4 !== _0n5) + y = modP(-y); + const p = new Point(x, y, _1n5); + p.assertValidity(); + return p; +} +var num = bytesToNumberBE; +function challenge(...args) { + return modN(num(taggedHash("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; +} +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m); + const k_ = modN(num(rand)); + if (k_ === _0n5) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + if (!schnorrVerify(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P = lift_x(num(pub)); + const r = num(sig.subarray(0, 32)); + if (!inRange(r, _1n5, secp256k1P)) + return false; + const s = num(sig.subarray(32, 64)); + if (!inRange(s, _1n5, secp256k1N)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); + const R = GmulAdd(P, s, modN(-e)); + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; + return true; + } catch (error) { + return false; + } +} +var schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod + } +}))(); +var isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ + // xNum + [ + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", + "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", + "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" + ], + // xDen + [ + "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", + "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ], + // yNum + [ + "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", + "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", + "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", + "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" + ], + // yDen + [ + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", + "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", + "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ] +].map((i) => i.map((j) => BigInt(j)))))(); +var mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { + A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), + B: BigInt("1771"), + Z: Fpk1.create(BigInt("-11")) +}))(); +var htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fpk1.create(scalars[0])); + return isoMap(x, y); +}, { + DST: "secp256k1_XMD:SHA-256_SSWU_RO_", + encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: "xmd", + hash: sha256 +}))(); +var hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); +var encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + +export { + secp256k1, + schnorr, + hashToCurve, + encodeToCurve +}; +/*! Bundled license information: + +@noble/hashes/esm/utils.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/utils.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/modular.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/curve.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/weierstrass.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/_shortw_utils.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/secp256k1.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) +*/ +//# sourceMappingURL=chunk-4L6P6TY5.js.map \ No newline at end of file diff --git a/dist/chunk-4L6P6TY5.js.map b/dist/chunk-4L6P6TY5.js.map new file mode 100644 index 0000000..c93a5cf --- /dev/null +++ b/dist/chunk-4L6P6TY5.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../node_modules/viem/node_modules/@noble/curves/src/_shortw_utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/secp256k1.ts"],"sourcesContent":["function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n// Falls back to Node.js built-in crypto for Node.js <=v14\n// See utils.ts for details.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { ahash, abytes, aexists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\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('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn: (arg: T, ...args: O) => R) {\n const map = new WeakMap();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n =/* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000) throw new Error('Cannot find square root: likely non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\nexport function FpLegendre(order: bigint) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f: IField, x: T): T => f.pow(x, legendreConst);\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendre = FpLegendre(f.ORDER);\n return (x: T): boolean => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType; // cached sqrtP\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\nfunction constTimeNegate>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\nfunction calcWOpts(W: number, bits: number) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n) break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0) continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0) curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger>(\n c: GroupConstructor,\n fieldN: IField,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe>(\n c: GroupConstructor,\n fieldN: IField,\n points: T[],\n windowSize: number\n) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = BigInt((1 << windowSize) - 1);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport {\n AffinePoint,\n BasicCurve,\n Group,\n GroupConstructor,\n validateBasic,\n wNAF,\n pippenger,\n} from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes, memoized, abool } from './utils.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n msm(points: ProjPointType[], scalars: bigint[]): ProjPointType;\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n CURVE: ReturnType>;\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = ut.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint) {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType): CurvePointsRes {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // Our custom check \"just in case\"\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n ut.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || ut.isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { CHash } from './abstract/utils.js';\nimport { CurveType, weierstrass } from './abstract/weierstrass.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.js';\nimport { IField, mod } from './modular.js';\nimport type { CHash } from './utils.js';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js';\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\ntype UnicodeOrBytes = string | Uint8Array;\nexport type Opts = {\n DST: UnicodeOrBytes;\n p: bigint;\n m: number;\n k: number;\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction anum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\n// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n// Produces a uniformly random byte string using an extendable-output function (XOF) H.\n// 1. The collision resistance of H MUST be at least k bits.\n// 2. H MUST be an XOF that has been proved indifferentiable from\n// a random oracle under a reasonable cryptographic assumption.\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\n * https://www.rfc-editor.org/rfc/rfc9380#section-5.2\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n abytes(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\nexport interface H2CPoint extends Group> {\n add(rhs: H2CPoint): H2CPoint;\n toAffine(iz?: bigint): AffinePoint;\n clearCofactor(): H2CPoint;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor extends GroupConstructor> {\n fromAffine(ap: AffinePoint): H2CPoint;\n}\n\nexport type MapToCurve = (scalar: bigint[]) => AffinePoint;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\n\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n def: Opts & { encodeDST?: UnicodeOrBytes }\n) {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts);\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts);\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]) {\n if (!Array.isArray(scalars)) throw new Error('mapToCurve: expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('mapToCurve: expected array of bigints');\n const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport {\n inRange,\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n numberToBytesBE,\n} from './abstract/utils.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,GAAS;AACxB,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI;AAAG,UAAM,IAAI,MAAM,oCAAoC,CAAC;AAC9F;AAGA,SAAS,QAAQ,GAAU;AACzB,SAAO,aAAa,cAAe,YAAY,OAAO,CAAC,KAAK,EAAE,YAAY,SAAS;AACrF;AAEA,SAAS,OAAO,MAA8B,SAAiB;AAC7D,MAAI,CAAC,QAAQ,CAAC;AAAG,UAAM,IAAI,MAAM,qBAAqB;AACtD,MAAI,QAAQ,SAAS,KAAK,CAAC,QAAQ,SAAS,EAAE,MAAM;AAClD,UAAM,IAAI,MAAM,mCAAmC,UAAU,kBAAkB,EAAE,MAAM;AAC3F;AAQA,SAAS,MAAM,GAAO;AACpB,MAAI,OAAO,MAAM,cAAc,OAAO,EAAE,WAAW;AACjD,UAAM,IAAI,MAAM,iDAAiD;AACnE,UAAQ,EAAE,SAAS;AACnB,UAAQ,EAAE,QAAQ;AACpB;AAEA,SAAS,QAAQ,UAAe,gBAAgB,MAAI;AAClD,MAAI,SAAS;AAAW,UAAM,IAAI,MAAM,kCAAkC;AAC1E,MAAI,iBAAiB,SAAS;AAAU,UAAM,IAAI,MAAM,uCAAuC;AACjG;AACA,SAAS,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B,GACA;EACE,KAAK;EACL,WAAW;EACX,GAAG,KAAK;EACR,GAAG;EACH,GAAG;EACH,QAAQ;EACR,MAAM;CACP,GACD;AACG,IAAM,cAA+B,uBAAM,IAAI,aAAY;AAC3D,IAAM,gBAAiC,uBAAM,IAAI,eAAc;","names":["abytes","concatBytes","isBytes","utf8ToBytes","num","_0n","_1n","_2n","num","num","_0n","_1n","bitLen","_0n","_1n","num","num","_1n","_0n","_1n","wbits","num","_0n","abytes","_1n","_2n","_3n","_4n","toBytes","concatBytes","isBytes","Point","a","modN","randomBytes","tv5","c1","c2","abytes","concatBytes","utf8ToBytes","Point","_1n","_2n","_3n","_0n","concatBytes"]} \ No newline at end of file diff --git a/dist/chunk-KSHJJL6X.js b/dist/chunk-KSHJJL6X.js new file mode 100644 index 0000000..c539aea --- /dev/null +++ b/dist/chunk-KSHJJL6X.js @@ -0,0 +1,4019 @@ +// ../../node_modules/abitype/dist/esm/version.js +var version = "1.0.7"; + +// ../../node_modules/abitype/dist/esm/errors.js +var BaseError = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; + const docsPath4 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath; + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsPath4 ? [`Docs: https://abitype.dev${docsPath4}`] : [], + ...details ? [`Details: ${details}`] : [], + `Version: abitype@${version}` + ].join("\n"); + super(message); + 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: "AbiTypeError" + }); + if (args.cause) + this.cause = args.cause; + this.details = details; + this.docsPath = docsPath4; + this.metaMessages = args.metaMessages; + this.shortMessage = shortMessage; + } +}; + +// ../../node_modules/abitype/dist/esm/regex.js +function execTyped(regex, string) { + const match = regex.exec(string); + return match?.groups; +} +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)?$/; +var isTupleRegex = /^\(.+?\).*?$/; + +// ../../node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js +var tupleRegex = /^tuple(?(\[(\d*)\])*)$/; +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 + }); + } + if ("indexed" in abiParameter && abiParameter.indexed) + type = `${type} indexed`; + if (abiParameter.name) + return `${type} ${abiParameter.name}`; + return type; +} + +// ../../node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js +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; +} + +// ../../node_modules/abitype/dist/esm/human-readable/formatAbiItem.js +function formatAbiItem(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)})` : ""}`; + if (abiItem.type === "event") + return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "error") + return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "constructor") + return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; + if (abiItem.type === "fallback") + return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; + return "receive() external payable"; +} + +// ../../node_modules/abitype/dist/esm/human-readable/runtime/signatures.js +var errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; +function isErrorSignature(signature) { + return errorSignatureRegex.test(signature); +} +function execErrorSignature(signature) { + return execTyped(errorSignatureRegex, signature); +} +var eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; +function isEventSignature(signature) { + return eventSignatureRegex.test(signature); +} +function execEventSignature(signature) { + return execTyped(eventSignatureRegex, signature); +} +var functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; +function isFunctionSignature(signature) { + return functionSignatureRegex.test(signature); +} +function execFunctionSignature(signature) { + return execTyped(functionSignatureRegex, signature); +} +var structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; +function isStructSignature(signature) { + return structSignatureRegex.test(signature); +} +function execStructSignature(signature) { + return execTyped(structSignatureRegex, signature); +} +var constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; +function isConstructorSignature(signature) { + return constructorSignatureRegex.test(signature); +} +function execConstructorSignature(signature) { + return execTyped(constructorSignatureRegex, signature); +} +var fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; +function isFallbackSignature(signature) { + return fallbackSignatureRegex.test(signature); +} +var receiveSignatureRegex = /^receive\(\) external payable$/; +function isReceiveSignature(signature) { + return receiveSignatureRegex.test(signature); +} +var eventModifiers = /* @__PURE__ */ new Set(["indexed"]); +var functionModifiers = /* @__PURE__ */ new Set([ + "calldata", + "memory", + "storage" +]); + +// ../../node_modules/abitype/dist/esm/human-readable/errors/abiItem.js +var UnknownTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [ + `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownTypeError" + }); + } +}; +var UnknownSolidityTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [`Type "${type}" is not a valid ABI type.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSolidityTypeError" + }); + } +}; + +// ../../node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js +var InvalidParameterError = class extends BaseError { + constructor({ param }) { + super("Invalid ABI parameter.", { + details: param + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParameterError" + }); + } +}; +var SolidityProtectedKeywordError = class extends BaseError { + constructor({ param, name }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SolidityProtectedKeywordError" + }); + } +}; +var InvalidModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidModifierError" + }); + } +}; +var InvalidFunctionModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, + `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidFunctionModifierError" + }); + } +}; +var InvalidAbiTypeParameterError = class extends BaseError { + constructor({ abiParameter }) { + super("Invalid ABI parameter.", { + details: JSON.stringify(abiParameter, null, 2), + metaMessages: ["ABI parameter type is invalid."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiTypeParameterError" + }); + } +}; + +// ../../node_modules/abitype/dist/esm/human-readable/errors/signature.js +var InvalidSignatureError = class extends BaseError { + constructor({ signature, type }) { + super(`Invalid ${type} signature.`, { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidSignatureError" + }); + } +}; +var UnknownSignatureError = class extends BaseError { + constructor({ signature }) { + super("Unknown signature.", { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSignatureError" + }); + } +}; +var InvalidStructSignatureError = class extends BaseError { + constructor({ signature }) { + super("Invalid struct signature.", { + details: signature, + metaMessages: ["No properties exist."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidStructSignatureError" + }); + } +}; + +// ../../node_modules/abitype/dist/esm/human-readable/errors/struct.js +var CircularReferenceError = class extends BaseError { + constructor({ type }) { + super("Circular reference detected.", { + metaMessages: [`Struct "${type}" is a circular reference.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "CircularReferenceError" + }); + } +}; + +// ../../node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js +var InvalidParenthesisError = class extends BaseError { + constructor({ current, depth }) { + super("Unbalanced parentheses.", { + metaMessages: [ + `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` + ], + details: `Depth "${depth}"` + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParenthesisError" + }); + } +}; + +// ../../node_modules/abitype/dist/esm/human-readable/runtime/cache.js +function getParameterCacheKey(param, type, structs) { + let structKey = ""; + if (structs) + for (const struct of Object.entries(structs)) { + if (!struct) + continue; + let propertyKey = ""; + for (const property of struct[1]) { + propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`; + } + structKey += `(${struct[0]}{${propertyKey}})`; + } + if (type) + return `${type}:${param}${structKey}`; + return param; +} +var parameterCache = /* @__PURE__ */ new Map([ + // Unnamed + ["address", { type: "address" }], + ["bool", { type: "bool" }], + ["bytes", { type: "bytes" }], + ["bytes32", { type: "bytes32" }], + ["int", { type: "int256" }], + ["int256", { type: "int256" }], + ["string", { type: "string" }], + ["uint", { type: "uint256" }], + ["uint8", { type: "uint8" }], + ["uint16", { type: "uint16" }], + ["uint24", { type: "uint24" }], + ["uint32", { type: "uint32" }], + ["uint64", { type: "uint64" }], + ["uint96", { type: "uint96" }], + ["uint112", { type: "uint112" }], + ["uint160", { type: "uint160" }], + ["uint192", { type: "uint192" }], + ["uint256", { type: "uint256" }], + // Named + ["address owner", { type: "address", name: "owner" }], + ["address to", { type: "address", name: "to" }], + ["bool approved", { type: "bool", name: "approved" }], + ["bytes _data", { type: "bytes", name: "_data" }], + ["bytes data", { type: "bytes", name: "data" }], + ["bytes signature", { type: "bytes", name: "signature" }], + ["bytes32 hash", { type: "bytes32", name: "hash" }], + ["bytes32 r", { type: "bytes32", name: "r" }], + ["bytes32 root", { type: "bytes32", name: "root" }], + ["bytes32 s", { type: "bytes32", name: "s" }], + ["string name", { type: "string", name: "name" }], + ["string symbol", { type: "string", name: "symbol" }], + ["string tokenURI", { type: "string", name: "tokenURI" }], + ["uint tokenId", { type: "uint256", name: "tokenId" }], + ["uint8 v", { type: "uint8", name: "v" }], + ["uint256 balance", { type: "uint256", name: "balance" }], + ["uint256 tokenId", { type: "uint256", name: "tokenId" }], + ["uint256 value", { type: "uint256", name: "value" }], + // Indexed + [ + "event:address indexed from", + { type: "address", name: "from", indexed: true } + ], + ["event:address indexed to", { type: "address", name: "to", indexed: true }], + [ + "event:uint indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ], + [ + "event:uint256 indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ] +]); + +// ../../node_modules/abitype/dist/esm/human-readable/runtime/utils.js +function parseSignature(signature, structs = {}) { + if (isFunctionSignature(signature)) { + const match = execFunctionSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "function" }); + const inputParams = splitParameters(match.parameters); + const inputs = []; + const inputLength = inputParams.length; + for (let i = 0; i < inputLength; i++) { + inputs.push(parseAbiParameter(inputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); + } + const outputs = []; + if (match.returns) { + const outputParams = splitParameters(match.returns); + const outputLength = outputParams.length; + for (let i = 0; i < outputLength; i++) { + outputs.push(parseAbiParameter(outputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); + } + } + return { + name: match.name, + type: "function", + stateMutability: match.stateMutability ?? "nonpayable", + inputs, + outputs + }; + } + if (isEventSignature(signature)) { + const match = execEventSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "event" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { + modifiers: eventModifiers, + structs, + type: "event" + })); + } + return { name: match.name, type: "event", inputs: abiParameters }; + } + if (isErrorSignature(signature)) { + const match = execErrorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "error" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); + } + return { name: match.name, type: "error", inputs: abiParameters }; + } + if (isConstructorSignature(signature)) { + const match = execConstructorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "constructor" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); + } + return { + type: "constructor", + stateMutability: match.stateMutability ?? "nonpayable", + inputs: abiParameters + }; + } + if (isFallbackSignature(signature)) + return { type: "fallback" }; + if (isReceiveSignature(signature)) + return { + type: "receive", + stateMutability: "payable" + }; + throw new UnknownSignatureError({ signature }); +} +var abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; +var abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; +var dynamicIntegerRegex = /^u?int$/; +function parseAbiParameter(param, options) { + const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs); + if (parameterCache.has(parameterCacheKey)) + return parameterCache.get(parameterCacheKey); + const isTuple = isTupleRegex.test(param); + const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); + if (!match) + throw new InvalidParameterError({ param }); + if (match.name && isSolidityKeyword(match.name)) + throw new SolidityProtectedKeywordError({ param, name: match.name }); + const name = match.name ? { name: match.name } : {}; + const indexed = match.modifier === "indexed" ? { indexed: true } : {}; + const structs = options?.structs ?? {}; + let type; + let components = {}; + if (isTuple) { + type = "tuple"; + const params = splitParameters(match.type); + const components_ = []; + const length = params.length; + for (let i = 0; i < length; i++) { + components_.push(parseAbiParameter(params[i], { structs })); + } + components = { components: components_ }; + } else if (match.type in structs) { + type = "tuple"; + components = { components: structs[match.type] }; + } else if (dynamicIntegerRegex.test(match.type)) { + type = `${match.type}256`; + } else { + type = match.type; + if (!(options?.type === "struct") && !isSolidityType(type)) + throw new UnknownSolidityTypeError({ type }); + } + if (match.modifier) { + if (!options?.modifiers?.has?.(match.modifier)) + throw new InvalidModifierError({ + param, + type: options?.type, + modifier: match.modifier + }); + if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) + throw new InvalidFunctionModifierError({ + param, + type: options?.type, + modifier: match.modifier + }); + } + const abiParameter = { + type: `${type}${match.array ?? ""}`, + ...name, + ...indexed, + ...components + }; + parameterCache.set(parameterCacheKey, abiParameter); + return abiParameter; +} +function splitParameters(params, result = [], current = "", depth = 0) { + const length = params.trim().length; + for (let i = 0; i < length; i++) { + const char = params[i]; + const tail = params.slice(i + 1); + switch (char) { + case ",": + return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); + case "(": + return splitParameters(tail, result, `${current}${char}`, depth + 1); + case ")": + return splitParameters(tail, result, `${current}${char}`, depth - 1); + default: + return splitParameters(tail, result, `${current}${char}`, depth); + } + } + if (current === "") + return result; + if (depth !== 0) + throw new InvalidParenthesisError({ current, depth }); + result.push(current.trim()); + return result; +} +function isSolidityType(type) { + return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type); +} +var protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; +function isSolidityKeyword(name) { + return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name); +} +function isValidDataLocation(type, isArray) { + return isArray || type === "bytes" || type === "string" || type === "tuple"; +} + +// ../../node_modules/abitype/dist/esm/human-readable/runtime/structs.js +function parseStructs(signatures) { + const shallowStructs = {}; + const signaturesLength = signatures.length; + for (let i = 0; i < signaturesLength; i++) { + const signature = signatures[i]; + if (!isStructSignature(signature)) + continue; + const match = execStructSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "struct" }); + const properties = match.properties.split(";"); + const components = []; + const propertiesLength = properties.length; + for (let k = 0; k < propertiesLength; k++) { + const property = properties[k]; + const trimmed = property.trim(); + if (!trimmed) + continue; + const abiParameter = parseAbiParameter(trimmed, { + type: "struct" + }); + components.push(abiParameter); + } + if (!components.length) + throw new InvalidStructSignatureError({ signature }); + shallowStructs[match.name] = components; + } + const resolvedStructs = {}; + const entries = Object.entries(shallowStructs); + const entriesLength = entries.length; + for (let i = 0; i < entriesLength; i++) { + const [name, parameters] = entries[i]; + resolvedStructs[name] = resolveStructs(parameters, shallowStructs); + } + return resolvedStructs; +} +var typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; +function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { + const components = []; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + const isTuple = isTupleRegex.test(abiParameter.type); + if (isTuple) + components.push(abiParameter); + else { + const match = execTyped(typeWithoutTupleRegex, abiParameter.type); + if (!match?.type) + throw new InvalidAbiTypeParameterError({ abiParameter }); + const { array, type } = match; + if (type in structs) { + if (ancestors.has(type)) + throw new CircularReferenceError({ type }); + components.push({ + ...abiParameter, + type: `tuple${array ?? ""}`, + components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) + }); + } else { + if (isSolidityType(type)) + components.push(abiParameter); + else + throw new UnknownTypeError({ type }); + } + } + } + return components; +} + +// ../../node_modules/abitype/dist/esm/human-readable/parseAbi.js +function parseAbi(signatures) { + const structs = parseStructs(signatures); + const abi = []; + const length = signatures.length; + for (let i = 0; i < length; i++) { + const signature = signatures[i]; + if (isStructSignature(signature)) + continue; + abi.push(parseSignature(signature, structs)); + } + return abi; +} + +// ../../node_modules/viem/_esm/accounts/utils/parseAccount.js +function parseAccount(account) { + if (typeof account === "string") + return { address: account, type: "json-rpc" }; + return account; +} + +// ../../node_modules/viem/_esm/constants/abis.js +var multicall3Abi = [ + { + inputs: [ + { + components: [ + { + name: "target", + type: "address" + }, + { + name: "allowFailure", + type: "bool" + }, + { + name: "callData", + type: "bytes" + } + ], + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + name: "success", + type: "bool" + }, + { + name: "returnData", + type: "bytes" + } + ], + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "view", + type: "function" + } +]; +var universalResolverErrors = [ + { + inputs: [], + name: "ResolverNotFound", + type: "error" + }, + { + inputs: [], + name: "ResolverWildcardNotSupported", + type: "error" + }, + { + inputs: [], + name: "ResolverNotContract", + type: "error" + }, + { + inputs: [ + { + name: "returnData", + type: "bytes" + } + ], + name: "ResolverError", + type: "error" + }, + { + inputs: [ + { + components: [ + { + name: "status", + type: "uint16" + }, + { + name: "message", + type: "string" + } + ], + name: "errors", + type: "tuple[]" + } + ], + name: "HttpError", + type: "error" + } +]; +var universalResolverResolveAbi = [ + ...universalResolverErrors, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + }, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" }, + { name: "gateways", type: "string[]" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + } +]; +var universalResolverReverseAbi = [ + ...universalResolverErrors, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [{ type: "bytes", name: "reverseName" }], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + }, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [ + { type: "bytes", name: "reverseName" }, + { type: "string[]", name: "gateways" } + ], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + } +]; + +// ../../node_modules/viem/_esm/constants/contract.js +var aggregate3Signature = "0x82ad56cb"; + +// ../../node_modules/viem/_esm/constants/contracts.js +var deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; +var deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; + +// ../../node_modules/viem/_esm/errors/version.js +var version2 = "2.21.58"; + +// ../../node_modules/viem/_esm/errors/base.js +var errorConfig = { + getDocsUrl: ({ docsBaseUrl, docsPath: docsPath4 = "", docsSlug }) => docsPath4 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath4}${docsSlug ? `#${docsSlug}` : ""}` : void 0, + version: `viem@${version2}` +}; +var BaseError2 = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = (() => { + if (args.cause instanceof _BaseError) + return args.cause.details; + if (args.cause?.message) + return args.cause.message; + return args.details; + })(); + const docsPath4 = (() => { + if (args.cause instanceof _BaseError) + return args.cause.docsPath || args.docsPath; + return args.docsPath; + })(); + const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath4 }); + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsUrl ? [`Docs: ${docsUrl}`] : [], + ...details ? [`Details: ${details}`] : [], + ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] + ].join("\n"); + super(message, args.cause ? { cause: args.cause } : void 0); + 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, "version", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + this.details = details; + this.docsPath = docsPath4; + this.metaMessages = args.metaMessages; + this.name = args.name ?? this.name; + this.shortMessage = shortMessage; + this.version = version2; + } + walk(fn) { + return walk(this, fn); + } +}; +function walk(err, fn) { + if (fn?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) + return walk(err.cause, fn); + return fn ? null : err; +} + +// ../../node_modules/viem/_esm/errors/chain.js +var ChainDoesNotSupportContract = class extends BaseError2 { + constructor({ blockNumber, chain, contract }) { + super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + metaMessages: [ + "This could be due to any of the following:", + ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ + `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` + ] : [ + `- The chain does not have the contract "${contract.name}" configured.` + ] + ], + name: "ChainDoesNotSupportContract" + }); + } +}; +var ClientChainNotConfiguredError = class extends BaseError2 { + constructor() { + super("No chain was provided to the Client.", { + name: "ClientChainNotConfiguredError" + }); + } +}; +var InvalidChainIdError = class extends BaseError2 { + constructor({ chainId }) { + super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + } +}; + +// ../../node_modules/viem/_esm/constants/solidity.js +var solidityError = { + inputs: [ + { + name: "message", + type: "string" + } + ], + name: "Error", + type: "error" +}; +var solidityPanic = { + inputs: [ + { + name: "reason", + type: "uint256" + } + ], + name: "Panic", + type: "error" +}; + +// ../../node_modules/viem/_esm/utils/abi/formatAbiItem.js +function formatAbiItem2(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}` : ""); +} + +// ../../node_modules/viem/_esm/utils/data/isHex.js +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"); +} + +// ../../node_modules/viem/_esm/utils/data/size.js +function size(value) { + if (isHex(value, { strict: false })) + return Math.ceil((value.length - 2) / 2); + return value.length; +} + +// ../../node_modules/viem/_esm/errors/abi.js +var AbiConstructorNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath4 }) { + 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: docsPath4, + name: "AbiConstructorNotFoundError" + }); + } +}; +var AbiConstructorParamsNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath4 }) { + 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: docsPath4, + name: "AbiConstructorParamsNotFoundError" + }); + } +}; +var AbiDecodingDataSizeTooSmallError = class extends BaseError2 { + constructor({ data, params, size: size2 }) { + super([`Data size of ${size2} bytes is too small for given parameters.`].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size2} bytes)` + ], + name: "AbiDecodingDataSizeTooSmallError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + this.params = params; + this.size = size2; + } +}; +var AbiDecodingZeroDataError = class extends BaseError2 { + constructor() { + super('Cannot decode zero data ("0x") with ABI parameters.', { + name: "AbiDecodingZeroDataError" + }); + } +}; +var AbiEncodingArrayLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength, type }) { + super([ + `ABI encoding array length mismatch for type ${type}.`, + `Expected length: ${expectedLength}`, + `Given length: ${givenLength}` + ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); + } +}; +var AbiEncodingBytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + } +}; +var AbiEncodingLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding params/values length mismatch.", + `Expected length (params): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); + } +}; +var AbiErrorSignatureNotFoundError = class extends BaseError2 { + constructor(signature, { docsPath: docsPath4 }) { + super([ + `Encoded error signature "${signature}" not found on ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` + ].join("\n"), { + docsPath: docsPath4, + name: "AbiErrorSignatureNotFoundError" + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.signature = signature; + } +}; +var AbiFunctionNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath4 } = {}) { + 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: docsPath4, + name: "AbiFunctionNotFoundError" + }); + } +}; +var AbiFunctionOutputsNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath4 }) { + super([ + `Function "${functionName}" does not contain any \`outputs\` on ABI.`, + "Cannot decode function result without knowing what the parameter types are.", + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath4, + name: "AbiFunctionOutputsNotFoundError" + }); + } +}; +var AbiItemAmbiguityError = class extends BaseError2 { + constructor(x, y) { + super("Found ambiguous types in overloaded ABI items.", { + metaMessages: [ + `\`${x.type}\` in \`${formatAbiItem2(x.abiItem)}\`, and`, + `\`${y.type}\` in \`${formatAbiItem2(y.abiItem)}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ], + name: "AbiItemAmbiguityError" + }); + } +}; +var BytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, givenSize }) { + super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { + name: "BytesSizeMismatchError" + }); + } +}; +var InvalidAbiEncodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath4 }) { + super([ + `Type "${type}" is not a valid encoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath4, name: "InvalidAbiEncodingType" }); + } +}; +var InvalidAbiDecodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath4 }) { + super([ + `Type "${type}" is not a valid decoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath4, name: "InvalidAbiDecodingType" }); + } +}; +var InvalidArrayError = class extends BaseError2 { + constructor(value) { + super([`Value "${value}" is not a valid array.`].join("\n"), { + name: "InvalidArrayError" + }); + } +}; +var InvalidDefinitionTypeError = class extends BaseError2 { + constructor(type) { + super([ + `"${type}" is not a valid definition type.`, + 'Valid types: "function", "event", "error"' + ].join("\n"), { name: "InvalidDefinitionTypeError" }); + } +}; + +// ../../node_modules/viem/_esm/errors/data.js +var SliceOffsetOutOfBoundsError = class extends BaseError2 { + constructor({ offset, position, size: size2 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); + } +}; +var SizeExceedsPaddingSizeError = class extends BaseError2 { + constructor({ size: size2, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); + } +}; +var InvalidBytesLengthError = class extends BaseError2 { + constructor({ size: size2, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); + } +}; + +// ../../node_modules/viem/_esm/utils/data/slice.js +function slice(value, start, end, { strict } = {}) { + if (isHex(value, { strict: false })) + return sliceHex(value, start, end, { + strict + }); + return sliceBytes(value, start, end, { + strict + }); +} +function assertStartOffset(value, start) { + if (typeof start === "number" && start > 0 && start > size(value) - 1) + throw new SliceOffsetOutOfBoundsError({ + offset: start, + position: "start", + size: size(value) + }); +} +function assertEndOffset(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError({ + offset: end, + position: "end", + size: size(value) + }); + } +} +function sliceBytes(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = value_.slice(start, end); + if (strict) + assertEndOffset(value, start, end); + return value; +} +function sliceHex(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; + if (strict) + assertEndOffset(value, start, end); + return value; +} + +// ../../node_modules/viem/_esm/utils/data/pad.js +function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) { + if (typeof hexOrBytes === "string") + return padHex(hexOrBytes, { dir, size: size2 }); + return padBytes(hexOrBytes, { dir, size: size2 }); +} +function padHex(hex_, { dir, size: size2 = 32 } = {}) { + if (size2 === null) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size2 * 2) + throw new SizeExceedsPaddingSizeError({ + size: Math.ceil(hex.length / 2), + targetSize: size2, + type: "hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; +} +function padBytes(bytes, { dir, size: size2 = 32 } = {}) { + if (size2 === null) + return bytes; + if (bytes.length > size2) + throw new SizeExceedsPaddingSizeError({ + size: bytes.length, + targetSize: size2, + type: "bytes" + }); + const paddedBytes = new Uint8Array(size2); + for (let i = 0; i < size2; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + } + return paddedBytes; +} + +// ../../node_modules/viem/_esm/errors/encoding.js +var IntegerOutOfRangeError = class extends BaseError2 { + constructor({ max, min, signed, size: size2, value }) { + super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); + } +}; +var InvalidBytesBooleanError = class extends BaseError2 { + constructor(bytes) { + super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { + name: "InvalidBytesBooleanError" + }); + } +}; +var SizeOverflowError = class extends BaseError2 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); + } +}; + +// ../../node_modules/viem/_esm/utils/data/trim.js +function trim(hexOrBytes, { dir = "left" } = {}) { + let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; + let sliceLength = 0; + for (let i = 0; i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; + } + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + if (typeof hexOrBytes === "string") { + if (data.length === 1 && dir === "right") + data = `${data}0`; + return `0x${data.length % 2 === 1 ? `0${data}` : data}`; + } + return data; +} + +// ../../node_modules/viem/_esm/utils/encoding/fromHex.js +function assertSize(hexOrBytes, { size: size2 }) { + if (size(hexOrBytes) > size2) + throw new SizeOverflowError({ + givenSize: size(hexOrBytes), + maxSize: size2 + }); +} +function hexToBigInt(hex, opts = {}) { + const { signed } = opts; + if (opts.size) + assertSize(hex, { size: opts.size }); + const value = BigInt(hex); + if (!signed) + return value; + const size2 = (hex.length - 2) / 2; + const max = (1n << BigInt(size2) * 8n - 1n) - 1n; + if (value <= max) + return value; + return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; +} +function hexToNumber(hex, opts = {}) { + return Number(hexToBigInt(hex, opts)); +} + +// ../../node_modules/viem/_esm/utils/encoding/toHex.js +var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); +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(value, opts); +} +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; +} +function bytesToHex(value, opts = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) { + string += hexes[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; +} +function numberToHex(value_, opts = {}) { + const { signed, size: size2 } = opts; + const value = BigInt(value_); + let maxValue; + if (size2) { + if (signed) + maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size2) * 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}` : void 0, + min: `${minValue}${suffix}`, + signed, + size: size2, + value: `${value_}${suffix}` + }); + } + const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; + if (size2) + return pad(hex, { size: size2 }); + return hex; +} +var encoder = /* @__PURE__ */ new TextEncoder(); +function stringToHex(value_, opts = {}) { + const value = encoder.encode(value_); + return bytesToHex(value, opts); +} + +// ../../node_modules/viem/_esm/utils/encoding/toBytes.js +var encoder2 = /* @__PURE__ */ new TextEncoder(); +function toBytes(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(value, opts); + return stringToBytes(value, opts); +} +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; +} +var 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 void 0; +} +function hexToBytes(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 === void 0 || nibbleRight === void 0) { + throw new BaseError2(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); + } + bytes[index] = nibbleLeft * 16 + nibbleRight; + } + return bytes; +} +function numberToBytes(value, opts) { + const hex = numberToHex(value, opts); + return hexToBytes(hex); +} +function stringToBytes(value, opts = {}) { + const bytes = encoder2.encode(value); + if (typeof opts.size === "number") { + assertSize(bytes, { size: opts.size }); + return pad(bytes, { dir: "right", size: opts.size }); + } + return bytes; +} + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/_assert.js +function anumber(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); +} +function aexists(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 aoutput(out, instance) { + abytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } +} + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/_u64.js +var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n = /* @__PURE__ */ BigInt(32); +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(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(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +var rotlSH = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/utils.js +var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr = (word, shift) => word << 32 - shift | word >>> shift; +var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes2(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + abytes(data); + return data; +} +var Hash = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/sha3.js +var SHA3_PI = []; +var SHA3_ROTL = []; +var _SHA3_IOTA = []; +var _0n = /* @__PURE__ */ BigInt(0); +var _1n = /* @__PURE__ */ BigInt(1); +var _2n = /* @__PURE__ */ BigInt(2); +var _7n = /* @__PURE__ */ BigInt(7); +var _256n = /* @__PURE__ */ BigInt(256); +var _0x71n = /* @__PURE__ */ BigInt(113); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n; + for (let j = 0; j < 7; j++) { + R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n; + if (R & _2n) + t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n; + } + _SHA3_IOTA.push(t); +} +var [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); +var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); +var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + 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(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + 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]; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +var Keccak = class _Keccak extends Hash { + // 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; + anumber(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + const { blockLen, state } = this; + data = toBytes2(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; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(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) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(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; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +}; +var gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +var sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); +var sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); +var sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); +var sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); +var keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); +var keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); +var keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); +var keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); +var genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); +var shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); +var shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); + +// ../../node_modules/viem/_esm/utils/hash/keccak256.js +function keccak256(value, to_) { + const to = to_ || "hex"; + const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to === "bytes") + return bytes; + return toHex(bytes); +} + +// ../../node_modules/viem/_esm/utils/hash/hashSignature.js +var hash = (value) => keccak256(toBytes(value)); +function hashSignature(sig) { + return hash(sig); +} + +// ../../node_modules/viem/_esm/utils/hash/normalizeSignature.js +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 (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; + } + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; + } + if (!valid) + throw new BaseError2("Unable to normalize signature."); + return result; +} + +// ../../node_modules/viem/_esm/utils/hash/toSignature.js +var toSignature = (def) => { + const def_ = (() => { + if (typeof def === "string") + return def; + return formatAbiItem(def); + })(); + return normalizeSignature(def_); +}; + +// ../../node_modules/viem/_esm/utils/hash/toSignatureHash.js +function toSignatureHash(fn) { + return hashSignature(toSignature(fn)); +} + +// ../../node_modules/viem/_esm/utils/hash/toFunctionSelector.js +var toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); + +// ../../node_modules/viem/_esm/errors/address.js +var InvalidAddressError = class extends BaseError2 { + 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." + ], + name: "InvalidAddressError" + }); + } +}; + +// ../../node_modules/viem/_esm/utils/lru.js +var LruMap = class extends Map { + constructor(size2) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size2; + } + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); + } + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); + } + return this; + } +}; + +// ../../node_modules/viem/_esm/utils/address/isAddress.js +var addressRegex = /^0x[a-fA-F0-9]{40}$/; +var isAddressCache = /* @__PURE__ */ new LruMap(8192); +function isAddress(address, options) { + const { strict = true } = options ?? {}; + const cacheKey = `${address}.${strict}`; + if (isAddressCache.has(cacheKey)) + return isAddressCache.get(cacheKey); + const result = (() => { + if (!addressRegex.test(address)) + return false; + if (address.toLowerCase() === address) + return true; + if (strict) + return checksumAddress(address) === address; + return true; + })(); + isAddressCache.set(cacheKey, result); + return result; +} + +// ../../node_modules/viem/_esm/utils/address/getAddress.js +var checksumAddressCache = /* @__PURE__ */ new LruMap(8192); +function checksumAddress(address_, chainId) { + if (checksumAddressCache.has(`${address_}.${chainId}`)) + return checksumAddressCache.get(`${address_}.${chainId}`); + const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); + const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); + const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && address[i]) { + address[i] = address[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { + address[i + 1] = address[i + 1].toUpperCase(); + } + } + const result = `0x${address.join("")}`; + checksumAddressCache.set(`${address_}.${chainId}`, result); + return result; +} + +// ../../node_modules/viem/_esm/errors/cursor.js +var NegativeOffsetError = class extends BaseError2 { + constructor({ offset }) { + super(`Offset \`${offset}\` cannot be negative.`, { + name: "NegativeOffsetError" + }); + } +}; +var PositionOutOfBoundsError = class extends BaseError2 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); + } +}; +var RecursiveReadLimitExceededError = class extends BaseError2 { + constructor({ count, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); + } +}; + +// ../../node_modules/viem/_esm/utils/cursor.js +var staticCursor = { + bytes: new Uint8Array(), + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: /* @__PURE__ */ new Map(), + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position - offset; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position + offset; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes) { + this.assertPosition(this.position + bytes.length - 1); + this.bytes.set(bytes, this.position); + this.position += bytes.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size2) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size2 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count = this.getReadCount(); + this.positionReadCount.set(this.position, count + 1); + if (count > 0) + this.recursiveReadCount++; + } +}; +function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor); + cursor.bytes = bytes; + cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + cursor.positionReadCount = /* @__PURE__ */ new Map(); + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; +} + +// ../../node_modules/viem/_esm/utils/encoding/fromBytes.js +function bytesToBigInt(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToBigInt(hex, opts); +} +function bytesToBool(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes); + } + if (bytes.length > 1 || bytes[0] > 1) + throw new InvalidBytesBooleanError(bytes); + return Boolean(bytes[0]); +} +function bytesToNumber(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToNumber(hex, opts); +} +function bytesToString(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes, { dir: "right" }); + } + return new TextDecoder().decode(bytes); +} + +// ../../node_modules/viem/_esm/utils/data/concat.js +function concat(values) { + if (typeof values[0] === "string") + return concatHex(values); + return concatBytes(values); +} +function concatBytes(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; + } + return result; +} +function concatHex(values) { + return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; +} + +// ../../node_modules/viem/_esm/utils/regex.js +var bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +var integerRegex2 = /^(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/encodeAbiParameters.js +function encodeAbiParameters(params, values) { + if (params.length !== values.length) + throw new AbiEncodingLengthMismatchError({ + expectedLength: params.length, + givenLength: values.length + }); + const preparedParams = prepareParams({ + params, + values + }); + const data = encodeParams(preparedParams); + if (data.length === 0) + return "0x"; + return data; +} +function prepareParams({ params, values }) { + const preparedParams = []; + for (let i = 0; i < params.length; i++) { + preparedParams.push(prepareParam({ param: params[i], value: values[i] })); + } + return preparedParams; +} +function prepareParam({ param, value }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray(value, { length, param: { ...param, type } }); + } + if (param.type === "tuple") { + return encodeTuple(value, { + param + }); + } + if (param.type === "address") { + return encodeAddress(value); + } + if (param.type === "bool") { + return encodeBool(value); + } + if (param.type.startsWith("uint") || param.type.startsWith("int")) { + const signed = param.type.startsWith("int"); + const [, , size2 = "256"] = integerRegex2.exec(param.type) ?? []; + return encodeNumber(value, { + signed, + size: Number(size2) + }); + } + if (param.type.startsWith("bytes")) { + return encodeBytes(value, { param }); + } + if (param.type === "string") { + return encodeString(value); + } + throw new InvalidAbiEncodingTypeError(param.type, { + docsPath: "/docs/contract/encodeAbiParameters" + }); +} +function encodeParams(preparedParams) { + let staticSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size(encoded); + } + const staticParams = []; + const dynamicParams = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) { + staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); + dynamicParams.push(encoded); + dynamicSize += size(encoded); + } else { + staticParams.push(encoded); + } + } + return concat([...staticParams, ...dynamicParams]); +} +function encodeAddress(value) { + if (!isAddress(value)) + throw new InvalidAddressError({ address: value }); + return { dynamic: false, encoded: padHex(value.toLowerCase()) }; +} +function encodeArray(value, { length, param }) { + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError(value); + if (!dynamic && value.length !== length) + throw new AbiEncodingArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${param.type}[${length}]` + }); + let dynamicChild = false; + const preparedParams = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParam({ param, value: value[i] }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParams.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encodeParams(preparedParams); + if (dynamic) { + const length2 = numberToHex(preparedParams.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 + }; + } + if (dynamicChild) + return { dynamic: true, encoded: data }; + } + return { + dynamic: false, + encoded: concat(preparedParams.map(({ encoded }) => encoded)) + }; +} +function encodeBytes(value, { param }) { + const [, paramSize] = param.type.split("bytes"); + const bytesSize = size(value); + if (!paramSize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padHex(value_, { + dir: "right", + size: Math.ceil((value.length - 2) / 2 / 32) * 32 + }); + return { + dynamic: true, + encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) + }; + } + if (bytesSize !== Number.parseInt(paramSize)) + throw new AbiEncodingBytesSizeMismatchError({ + expectedSize: Number.parseInt(paramSize), + value + }); + return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; +} +function encodeBool(value) { + if (typeof value !== "boolean") + throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padHex(boolToHex(value)) }; +} +function encodeNumber(value, { signed, size: size2 = 256 }) { + if (typeof size2 === "number") { + const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError({ + max: max.toString(), + min: min.toString(), + signed, + size: size2 / 8, + value: value.toString() + }); + } + return { + dynamic: false, + encoded: numberToHex(value, { + size: 32, + signed + }) + }; +} +function encodeString(value) { + const hexValue = stringToHex(value); + const partsLength = Math.ceil(size(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { + dir: "right" + })); + } + return { + dynamic: true, + encoded: concat([ + padHex(numberToHex(size(hexValue), { size: 32 })), + ...parts + ]) + }; +} +function encodeTuple(value, { param }) { + let dynamic = false; + const preparedParams = []; + for (let i = 0; i < param.components.length; i++) { + const param_ = param.components[i]; + const index = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParam({ + param: param_, + value: value[index] + }); + preparedParams.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } + return { + dynamic, + encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) + }; +} +function getArrayComponents(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; +} + +// ../../node_modules/viem/_esm/utils/abi/decodeAbiParameters.js +function decodeAbiParameters(params, data) { + const bytes = typeof data === "string" ? hexToBytes(data) : data; + const cursor = createCursor(bytes); + if (size(bytes) === 0 && params.length > 0) + throw new AbiDecodingZeroDataError(); + if (size(data) && size(data) < 32) + throw new AbiDecodingDataSizeTooSmallError({ + data: typeof data === "string" ? data : bytesToHex(data), + params, + size: size(data) + }); + let consumed = 0; + const values = []; + for (let i = 0; i < params.length; ++i) { + const param = params[i]; + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter(cursor, param, { + staticPosition: 0 + }); + consumed += consumed_; + values.push(data2); + } + return values; +} +function decodeParameter(cursor, param, { staticPosition }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray(cursor, { ...param, type }, { length, staticPosition }); + } + if (param.type === "tuple") + return decodeTuple(cursor, param, { staticPosition }); + if (param.type === "address") + return decodeAddress(cursor); + if (param.type === "bool") + return decodeBool(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber(cursor, param); + if (param.type === "string") + return decodeString(cursor, { staticPosition }); + throw new InvalidAbiDecodingTypeError(param.type, { + docsPath: "/docs/contract/decodeAbiParameters" + }); +} +var sizeOfLength = 32; +var sizeOfOffset = 32; +function decodeAddress(cursor) { + const value = cursor.readBytes(32); + return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; +} +function decodeArray(cursor, param, { length, staticPosition }) { + if (!length) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const startOfData = start + sizeOfLength; + cursor.setPosition(start); + const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); + const dynamicChild = hasDynamicChild(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0; i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const value2 = []; + for (let i = 0; i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter(cursor, param, { + staticPosition: start + }); + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } + let consumed = 0; + const value = []; + for (let i = 0; i < length; ++i) { + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: staticPosition + consumed + }); + consumed += consumed_; + value.push(data); + } + return [value, consumed]; +} +function decodeBool(cursor) { + return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; +} +function decodeBytes(cursor, param, { staticPosition }) { + const [_, size2] = param.type.split("bytes"); + if (!size2) { + const offset = bytesToNumber(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [bytesToHex(data), 32]; + } + const value = bytesToHex(cursor.readBytes(Number.parseInt(size2), 32)); + return [value, 32]; +} +function decodeNumber(cursor, param) { + const signed = param.type.startsWith("int"); + const size2 = Number.parseInt(param.type.split("int")[1] || "256"); + const value = cursor.readBytes(32); + return [ + size2 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), + 32 + ]; +} +function decodeTuple(cursor, param, { staticPosition }) { + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition: start + }); + consumed += consumed_; + value[hasUnnamedChild ? i : component?.name] = data; + } + cursor.setPosition(staticPosition + 32); + return [value, 32]; + } + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition + }); + value[hasUnnamedChild ? i : component?.name] = data; + consumed += consumed_; + } + return [value, consumed]; +} +function decodeString(cursor, { staticPosition }) { + const offset = bytesToNumber(cursor.readBytes(32)); + const start = staticPosition + offset; + cursor.setPosition(start); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; + } + const data = cursor.readBytes(length, 32); + const value = bytesToString(trim(data)); + cursor.setPosition(staticPosition + 32); + return [value, 32]; +} +function hasDynamicChild(param) { + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return param.components?.some(hasDynamicChild); + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) + return true; + return false; +} + +// ../../node_modules/viem/_esm/utils/abi/decodeErrorResult.js +function decodeErrorResult(parameters) { + const { abi, data } = parameters; + const signature = slice(data, 0, 4); + if (signature === "0x") + throw new AbiDecodingZeroDataError(); + const abi_ = [...abi || [], solidityError, solidityPanic]; + const abiItem = abi_.find((x) => x.type === "error" && signature === toFunctionSelector(formatAbiItem2(x))); + if (!abiItem) + throw new AbiErrorSignatureNotFoundError(signature, { + docsPath: "/docs/contract/decodeErrorResult" + }); + return { + abiItem, + args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, + errorName: abiItem.name + }; +} + +// ../../node_modules/viem/_esm/utils/stringify.js +var stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { + const value2 = typeof value_ === "bigint" ? value_.toString() : value_; + return typeof replacer === "function" ? replacer(key, value2) : value2; +}, space); + +// ../../node_modules/viem/_esm/utils/hash/toEventSelector.js +var toEventSelector = toSignatureHash; + +// ../../node_modules/viem/_esm/utils/abi/getAbiItem.js +function getAbiItem(parameters) { + const { abi, args = [], name } = parameters; + const isSelector = isHex(name, { strict: false }); + const abiItems = abi.filter((abiItem) => { + if (isSelector) { + if (abiItem.type === "function") + return toFunctionSelector(abiItem) === name; + if (abiItem.type === "event") + return toEventSelector(abiItem) === name; + return false; + } + return "name" in abiItem && abiItem.name === name; + }); + if (abiItems.length === 0) + return void 0; + if (abiItems.length === 1) + return abiItems[0]; + let matchedAbiItem = void 0; + for (const abiItem of abiItems) { + if (!("inputs" in abiItem)) + continue; + if (!args || args.length === 0) { + if (!abiItem.inputs || abiItem.inputs.length === 0) + return abiItem; + continue; + } + if (!abiItem.inputs) + continue; + if (abiItem.inputs.length === 0) + continue; + if (abiItem.inputs.length !== args.length) + continue; + const matched = args.every((arg, index) => { + const abiParameter = "inputs" in abiItem && abiItem.inputs[index]; + if (!abiParameter) + return false; + return isArgOfType(arg, abiParameter); + }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AbiItemAmbiguityError({ + abiItem, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem; + } + } + if (matchedAbiItem) + return matchedAbiItem; + return abiItems[0]; +} +function isArgOfType(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return isAddress(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index) => { + return isArgOfType(Object.values(arg)[index], component); + }); + if (/^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(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x) => isArgOfType(x, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } + return false; + } + } +} +function getAmbiguousTypes(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return isAddress(args[parameterIndex], { strict: false }); + if (types.includes("address") && types.includes("bytes")) + return isAddress(args[parameterIndex], { strict: false }); + return false; + })(); + if (ambiguous) + return types; + } + return; +} + +// ../../node_modules/viem/_esm/constants/unit.js +var etherUnits = { + gwei: 9, + wei: 18 +}; +var gweiUnits = { + ether: -9, + wei: 9 +}; + +// ../../node_modules/viem/_esm/utils/unit/formatUnits.js +function formatUnits(value, decimals) { + let display = value.toString(); + const negative = display.startsWith("-"); + if (negative) + display = display.slice(1); + display = display.padStart(decimals, "0"); + let [integer, fraction] = [ + display.slice(0, display.length - decimals), + display.slice(display.length - decimals) + ]; + fraction = fraction.replace(/(0+)$/, ""); + return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; +} + +// ../../node_modules/viem/_esm/utils/unit/formatEther.js +function formatEther(wei, unit = "wei") { + return formatUnits(wei, etherUnits[unit]); +} + +// ../../node_modules/viem/_esm/utils/unit/formatGwei.js +function formatGwei(wei, unit = "wei") { + return formatUnits(wei, gweiUnits[unit]); +} + +// ../../node_modules/viem/_esm/errors/stateOverride.js +var AccountStateConflictError = class extends BaseError2 { + constructor({ address }) { + super(`State for account "${address}" is set multiple times.`, { + name: "AccountStateConflictError" + }); + } +}; +var StateAssignmentConflictError = class extends BaseError2 { + constructor() { + super("state and stateDiff are set on the same account.", { + name: "StateAssignmentConflictError" + }); + } +}; +function prettyStateMapping(stateMapping) { + return stateMapping.reduce((pretty, { slot, value }) => { + return `${pretty} ${slot}: ${value} +`; + }, ""); +} +function prettyStateOverride(stateOverride) { + return stateOverride.reduce((pretty, { address, ...state }) => { + let val = `${pretty} ${address}: +`; + if (state.nonce) + val += ` nonce: ${state.nonce} +`; + if (state.balance) + val += ` balance: ${state.balance} +`; + if (state.code) + val += ` code: ${state.code} +`; + if (state.state) { + val += " state:\n"; + val += prettyStateMapping(state.state); + } + if (state.stateDiff) { + val += " stateDiff:\n"; + val += prettyStateMapping(state.stateDiff); + } + return val; + }, " State Override:\n").slice(0, -1); +} + +// ../../node_modules/viem/_esm/errors/transaction.js +function prettyPrint(args) { + const entries = Object.entries(args).map(([key, value]) => { + if (value === void 0 || value === false) + return null; + return [key, value]; + }).filter(Boolean); + const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); + return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +} +var FeeConflictError = class extends BaseError2 { + constructor() { + super([ + "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", + "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." + ].join("\n"), { name: "FeeConflictError" }); + } +}; +var InvalidLegacyVError = class extends BaseError2 { + constructor({ v }) { + super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, { + name: "InvalidLegacyVError" + }); + } +}; +var InvalidSerializableTransactionError = class extends BaseError2 { + constructor({ transaction }) { + super("Cannot infer a transaction type from provided transaction.", { + metaMessages: [ + "Provided Transaction:", + "{", + prettyPrint(transaction), + "}", + "", + "To infer the type, either provide:", + "- a `type` to the Transaction, or", + "- an EIP-1559 Transaction with `maxFeePerGas`, or", + "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", + "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", + "- an EIP-7702 Transaction with `authorizationList`, or", + "- a Legacy Transaction with `gasPrice`" + ], + name: "InvalidSerializableTransactionError" + }); + } +}; +var InvalidStorageKeySizeError = class extends BaseError2 { + constructor({ storageKey }) { + super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" }); + } +}; + +// ../../node_modules/viem/_esm/errors/utils.js +var getUrl = (url) => url; + +// ../../node_modules/viem/_esm/errors/contract.js +var CallExecutionError = class extends BaseError2 { + constructor(cause, { account: account_, docsPath: docsPath4, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride }) { + const account = account_ ? parseAccount(account_) : void 0; + let 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 + }); + if (stateOverride) { + prettyArgs += ` +${prettyStateOverride(stateOverride)}`; + } + super(cause.shortMessage, { + cause, + docsPath: docsPath4, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Raw Call Arguments:", + prettyArgs + ].filter(Boolean), + name: "CallExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } +}; +var CounterfactualDeploymentFailedError = class extends BaseError2 { + constructor({ factory }) { + super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, { + metaMessages: [ + "Please ensure:", + "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", + "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." + ], + name: "CounterfactualDeploymentFailedError" + }); + } +}; +var RawContractError = class extends BaseError2 { + constructor({ data, message }) { + super(message || "", { name: "RawContractError" }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + } +}; + +// ../../node_modules/viem/_esm/utils/abi/decodeFunctionResult.js +var docsPath = "/docs/contract/decodeFunctionResult"; +function decodeFunctionResult(parameters) { + const { abi, args, functionName, data } = parameters; + let abiItem = abi[0]; + if (functionName) { + const item = getAbiItem({ abi, args, name: functionName }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath }); + const values = decodeAbiParameters(abiItem.outputs, data); + if (values && values.length > 1) + return values; + if (values && values.length === 1) + return values[0]; + return void 0; +} + +// ../../node_modules/viem/_esm/utils/abi/encodeDeployData.js +var docsPath2 = "/docs/contract/encodeDeployData"; +function encodeDeployData(parameters) { + const { abi, args, bytecode } = parameters; + if (!args || args.length === 0) + return bytecode; + const description = abi.find((x) => "type" in x && x.type === "constructor"); + if (!description) + throw new AbiConstructorNotFoundError({ docsPath: docsPath2 }); + if (!("inputs" in description)) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 }); + if (!description.inputs || description.inputs.length === 0) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 }); + const data = encodeAbiParameters(description.inputs, args); + return concatHex([bytecode, data]); +} + +// ../../node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js +var docsPath3 = "/docs/contract/encodeFunctionData"; +function prepareEncodeFunctionData(parameters) { + const { abi, args, functionName } = parameters; + let abiItem = abi[0]; + if (functionName) { + const item = getAbiItem({ + abi, + args, + name: functionName + }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath3 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath3 }); + return { + abi: [abiItem], + functionName: toFunctionSelector(formatAbiItem2(abiItem)) + }; +} + +// ../../node_modules/viem/_esm/utils/abi/encodeFunctionData.js +function encodeFunctionData(parameters) { + const { args } = parameters; + const { abi, functionName } = (() => { + if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) + return parameters; + return prepareEncodeFunctionData(parameters); + })(); + const abiItem = abi[0]; + const signature = functionName; + const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; + return concatHex([signature, data ?? "0x"]); +} + +// ../../node_modules/viem/_esm/utils/chain/getChainContractAddress.js +function getChainContractAddress({ blockNumber, chain, contract: name }) { + const contract = chain?.contracts?.[name]; + if (!contract) + throw new ChainDoesNotSupportContract({ + chain, + contract: { name } + }); + if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) + throw new ChainDoesNotSupportContract({ + blockNumber, + chain, + contract: { + name, + blockCreated: contract.blockCreated + } + }); + return contract.address; +} + +// ../../node_modules/viem/_esm/errors/node.js +var ExecutionRevertedError = class extends BaseError2 { + constructor({ cause, message } = {}) { + const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); + super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { + cause, + name: "ExecutionRevertedError" + }); + } +}; +Object.defineProperty(ExecutionRevertedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 +}); +Object.defineProperty(ExecutionRevertedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /execution reverted/ +}); +var FeeCapTooHighError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { + cause, + name: "FeeCapTooHighError" + }); + } +}; +Object.defineProperty(FeeCapTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ +}); +var FeeCapTooLowError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { + cause, + name: "FeeCapTooLowError" + }); + } +}; +Object.defineProperty(FeeCapTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ +}); +var NonceTooHighError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); + } +}; +Object.defineProperty(NonceTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too high/ +}); +var NonceTooLowError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super([ + `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, + "Try increasing the nonce or find the latest nonce with `getTransactionCount`." + ].join("\n"), { cause, name: "NonceTooLowError" }); + } +}; +Object.defineProperty(NonceTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too low|transaction already imported|already known/ +}); +var NonceMaxValueError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); + } +}; +Object.defineProperty(NonceMaxValueError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce has max value/ +}); +var InsufficientFundsError = class extends BaseError2 { + constructor({ cause } = {}) { + super([ + "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." + ].join("\n"), { + cause, + metaMessages: [ + "This error could arise when the account does not have enough funds to:", + " - pay for the total gas fee,", + " - pay for the value to send.", + " ", + "The cost of the transaction is calculated as `gas * gas fee + value`, where:", + " - `gas` is the amount of gas needed for transaction to execute,", + " - `gas fee` is the gas fee,", + " - `value` is the amount of ether to send to the recipient." + ], + name: "InsufficientFundsError" + }); + } +}; +Object.defineProperty(InsufficientFundsError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /insufficient funds|exceeds transaction sender account balance/ +}); +var IntrinsicGasTooHighError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { + cause, + name: "IntrinsicGasTooHighError" + }); + } +}; +Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too high|gas limit reached/ +}); +var IntrinsicGasTooLowError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { + cause, + name: "IntrinsicGasTooLowError" + }); + } +}; +Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too low/ +}); +var TransactionTypeNotSupportedError = class extends BaseError2 { + constructor({ cause }) { + super("The transaction type is not supported for this chain.", { + cause, + name: "TransactionTypeNotSupportedError" + }); + } +}; +Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /transaction type not valid/ +}); +var TipAboveFeeCapError = class extends BaseError2 { + constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { + super([ + `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` + ].join("\n"), { + cause, + name: "TipAboveFeeCapError" + }); + } +}; +Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ +}); +var UnknownNodeError = class extends BaseError2 { + constructor({ cause }) { + super(`An error occurred while executing: ${cause?.shortMessage}`, { + cause, + name: "UnknownNodeError" + }); + } +}; + +// ../../node_modules/viem/_esm/errors/request.js +var HttpRequestError = class extends BaseError2 { + constructor({ body, cause, details, headers, status, url }) { + super("HTTP request failed.", { + cause, + details, + metaMessages: [ + status && `Status: ${status}`, + `URL: ${getUrl(url)}`, + body && `Request body: ${stringify(body)}` + ].filter(Boolean), + name: "HttpRequestError" + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "url", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.body = body; + this.headers = headers; + this.status = status; + this.url = url; + } +}; + +// ../../node_modules/viem/_esm/utils/errors/getNodeError.js +function getNodeError(err, args) { + const message = (err.details || "").toLowerCase(); + const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; + if (executionRevertedError instanceof BaseError2) + return new ExecutionRevertedError({ + cause: err, + message: executionRevertedError.details + }); + if (ExecutionRevertedError.nodeMessage.test(message)) + return new ExecutionRevertedError({ + cause: err, + message: err.details + }); + if (FeeCapTooHighError.nodeMessage.test(message)) + return new FeeCapTooHighError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (FeeCapTooLowError.nodeMessage.test(message)) + return new FeeCapTooLowError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (NonceTooHighError.nodeMessage.test(message)) + return new NonceTooHighError({ cause: err, nonce: args?.nonce }); + if (NonceTooLowError.nodeMessage.test(message)) + return new NonceTooLowError({ cause: err, nonce: args?.nonce }); + if (NonceMaxValueError.nodeMessage.test(message)) + return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); + if (InsufficientFundsError.nodeMessage.test(message)) + return new InsufficientFundsError({ cause: err }); + if (IntrinsicGasTooHighError.nodeMessage.test(message)) + return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); + if (IntrinsicGasTooLowError.nodeMessage.test(message)) + return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); + if (TransactionTypeNotSupportedError.nodeMessage.test(message)) + return new TransactionTypeNotSupportedError({ cause: err }); + if (TipAboveFeeCapError.nodeMessage.test(message)) + return new TipAboveFeeCapError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas, + maxPriorityFeePerGas: args?.maxPriorityFeePerGas + }); + return new UnknownNodeError({ + cause: err + }); +} + +// ../../node_modules/viem/_esm/utils/errors/getCallError.js +function getCallError(err, { docsPath: docsPath4, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new CallExecutionError(cause, { + docsPath: docsPath4, + ...args + }); +} + +// ../../node_modules/viem/_esm/utils/formatters/extract.js +function extract(value_, { format }) { + if (!format) + return {}; + const value = {}; + function extract_(formatted2) { + const keys = Object.keys(formatted2); + for (const key of keys) { + if (key in value_) + value[key] = value_[key]; + if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) + extract_(formatted2[key]); + } + } + const formatted = format(value_ || {}); + extract_(formatted); + return value; +} + +// ../../node_modules/viem/_esm/utils/formatters/transactionRequest.js +var rpcTransactionType = { + legacy: "0x0", + eip2930: "0x1", + eip1559: "0x2", + eip4844: "0x3", + eip7702: "0x4" +}; +function formatTransactionRequest(request) { + const rpcRequest = {}; + if (typeof request.authorizationList !== "undefined") + rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); + if (typeof request.accessList !== "undefined") + rpcRequest.accessList = request.accessList; + if (typeof request.blobVersionedHashes !== "undefined") + rpcRequest.blobVersionedHashes = request.blobVersionedHashes; + if (typeof request.blobs !== "undefined") { + if (typeof request.blobs[0] !== "string") + rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x)); + else + rpcRequest.blobs = request.blobs; + } + if (typeof request.data !== "undefined") + rpcRequest.data = request.data; + if (typeof request.from !== "undefined") + rpcRequest.from = request.from; + if (typeof request.gas !== "undefined") + rpcRequest.gas = numberToHex(request.gas); + if (typeof request.gasPrice !== "undefined") + rpcRequest.gasPrice = numberToHex(request.gasPrice); + if (typeof request.maxFeePerBlobGas !== "undefined") + rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); + if (typeof request.maxFeePerGas !== "undefined") + rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); + if (typeof request.maxPriorityFeePerGas !== "undefined") + rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); + if (typeof request.nonce !== "undefined") + rpcRequest.nonce = numberToHex(request.nonce); + if (typeof request.to !== "undefined") + rpcRequest.to = request.to; + if (typeof request.type !== "undefined") + rpcRequest.type = rpcTransactionType[request.type]; + if (typeof request.value !== "undefined") + rpcRequest.value = numberToHex(request.value); + return rpcRequest; +} +function formatAuthorizationList(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.contractAddress, + r: authorization.r, + s: authorization.s, + chainId: numberToHex(authorization.chainId), + nonce: numberToHex(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} + })); +} + +// ../../node_modules/viem/_esm/utils/promise/withResolvers.js +function withResolvers() { + let resolve = () => void 0; + let reject = () => void 0; + const promise = new Promise((resolve_, reject_) => { + resolve = resolve_; + reject = reject_; + }); + return { promise, resolve, reject }; +} + +// ../../node_modules/viem/_esm/utils/promise/createBatchScheduler.js +var schedulerCache = /* @__PURE__ */ new Map(); +function createBatchScheduler({ fn, id, shouldSplitBatch, wait = 0, sort }) { + const exec = async () => { + const scheduler = getScheduler(); + flush(); + const args = scheduler.map(({ args: args2 }) => args2); + if (args.length === 0) + return; + fn(args).then((data) => { + if (sort && Array.isArray(data)) + data.sort(sort); + for (let i = 0; i < scheduler.length; i++) { + const { resolve } = scheduler[i]; + resolve?.([data[i], data]); + } + }).catch((err) => { + for (let i = 0; i < scheduler.length; i++) { + const { reject } = scheduler[i]; + reject?.(err); + } + }); + }; + const flush = () => schedulerCache.delete(id); + const getBatchedArgs = () => getScheduler().map(({ args }) => args); + const getScheduler = () => schedulerCache.get(id) || []; + const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]); + return { + flush, + async schedule(args) { + const { promise, resolve, reject } = withResolvers(); + const split2 = shouldSplitBatch?.([...getBatchedArgs(), args]); + if (split2) + exec(); + const hasActiveScheduler = getScheduler().length > 0; + if (hasActiveScheduler) { + setScheduler({ args, resolve, reject }); + return promise; + } + setScheduler({ args, resolve, reject }); + setTimeout(exec, wait); + return promise; + } + }; +} + +// ../../node_modules/viem/_esm/utils/stateOverride.js +function serializeStateMapping(stateMapping) { + if (!stateMapping || stateMapping.length === 0) + return void 0; + return stateMapping.reduce((acc, { slot, value }) => { + if (slot.length !== 66) + throw new InvalidBytesLengthError({ + size: slot.length, + targetSize: 66, + type: "hex" + }); + if (value.length !== 66) + throw new InvalidBytesLengthError({ + size: value.length, + targetSize: 66, + type: "hex" + }); + acc[slot] = value; + return acc; + }, {}); +} +function serializeAccountStateOverride(parameters) { + const { balance, nonce, state, stateDiff, code } = parameters; + const rpcAccountStateOverride = {}; + if (code !== void 0) + rpcAccountStateOverride.code = code; + if (balance !== void 0) + rpcAccountStateOverride.balance = numberToHex(balance); + if (nonce !== void 0) + rpcAccountStateOverride.nonce = numberToHex(nonce); + if (state !== void 0) + rpcAccountStateOverride.state = serializeStateMapping(state); + if (stateDiff !== void 0) { + if (rpcAccountStateOverride.state) + throw new StateAssignmentConflictError(); + rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); + } + return rpcAccountStateOverride; +} +function serializeStateOverride(parameters) { + if (!parameters) + return void 0; + const rpcStateOverride = {}; + for (const { address, ...accountState } of parameters) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + if (rpcStateOverride[address]) + throw new AccountStateConflictError({ address }); + rpcStateOverride[address] = serializeAccountStateOverride(accountState); + } + return rpcStateOverride; +} + +// ../../node_modules/viem/_esm/constants/number.js +var maxInt8 = 2n ** (8n - 1n) - 1n; +var maxInt16 = 2n ** (16n - 1n) - 1n; +var maxInt24 = 2n ** (24n - 1n) - 1n; +var maxInt32 = 2n ** (32n - 1n) - 1n; +var maxInt40 = 2n ** (40n - 1n) - 1n; +var maxInt48 = 2n ** (48n - 1n) - 1n; +var maxInt56 = 2n ** (56n - 1n) - 1n; +var maxInt64 = 2n ** (64n - 1n) - 1n; +var maxInt72 = 2n ** (72n - 1n) - 1n; +var maxInt80 = 2n ** (80n - 1n) - 1n; +var maxInt88 = 2n ** (88n - 1n) - 1n; +var maxInt96 = 2n ** (96n - 1n) - 1n; +var maxInt104 = 2n ** (104n - 1n) - 1n; +var maxInt112 = 2n ** (112n - 1n) - 1n; +var maxInt120 = 2n ** (120n - 1n) - 1n; +var maxInt128 = 2n ** (128n - 1n) - 1n; +var maxInt136 = 2n ** (136n - 1n) - 1n; +var maxInt144 = 2n ** (144n - 1n) - 1n; +var maxInt152 = 2n ** (152n - 1n) - 1n; +var maxInt160 = 2n ** (160n - 1n) - 1n; +var maxInt168 = 2n ** (168n - 1n) - 1n; +var maxInt176 = 2n ** (176n - 1n) - 1n; +var maxInt184 = 2n ** (184n - 1n) - 1n; +var maxInt192 = 2n ** (192n - 1n) - 1n; +var maxInt200 = 2n ** (200n - 1n) - 1n; +var maxInt208 = 2n ** (208n - 1n) - 1n; +var maxInt216 = 2n ** (216n - 1n) - 1n; +var maxInt224 = 2n ** (224n - 1n) - 1n; +var maxInt232 = 2n ** (232n - 1n) - 1n; +var maxInt240 = 2n ** (240n - 1n) - 1n; +var maxInt248 = 2n ** (248n - 1n) - 1n; +var maxInt256 = 2n ** (256n - 1n) - 1n; +var minInt8 = -(2n ** (8n - 1n)); +var minInt16 = -(2n ** (16n - 1n)); +var minInt24 = -(2n ** (24n - 1n)); +var minInt32 = -(2n ** (32n - 1n)); +var minInt40 = -(2n ** (40n - 1n)); +var minInt48 = -(2n ** (48n - 1n)); +var minInt56 = -(2n ** (56n - 1n)); +var minInt64 = -(2n ** (64n - 1n)); +var minInt72 = -(2n ** (72n - 1n)); +var minInt80 = -(2n ** (80n - 1n)); +var minInt88 = -(2n ** (88n - 1n)); +var minInt96 = -(2n ** (96n - 1n)); +var minInt104 = -(2n ** (104n - 1n)); +var minInt112 = -(2n ** (112n - 1n)); +var minInt120 = -(2n ** (120n - 1n)); +var minInt128 = -(2n ** (128n - 1n)); +var minInt136 = -(2n ** (136n - 1n)); +var minInt144 = -(2n ** (144n - 1n)); +var minInt152 = -(2n ** (152n - 1n)); +var minInt160 = -(2n ** (160n - 1n)); +var minInt168 = -(2n ** (168n - 1n)); +var minInt176 = -(2n ** (176n - 1n)); +var minInt184 = -(2n ** (184n - 1n)); +var minInt192 = -(2n ** (192n - 1n)); +var minInt200 = -(2n ** (200n - 1n)); +var minInt208 = -(2n ** (208n - 1n)); +var minInt216 = -(2n ** (216n - 1n)); +var minInt224 = -(2n ** (224n - 1n)); +var minInt232 = -(2n ** (232n - 1n)); +var minInt240 = -(2n ** (240n - 1n)); +var minInt248 = -(2n ** (248n - 1n)); +var minInt256 = -(2n ** (256n - 1n)); +var maxUint8 = 2n ** 8n - 1n; +var maxUint16 = 2n ** 16n - 1n; +var maxUint24 = 2n ** 24n - 1n; +var maxUint32 = 2n ** 32n - 1n; +var maxUint40 = 2n ** 40n - 1n; +var maxUint48 = 2n ** 48n - 1n; +var maxUint56 = 2n ** 56n - 1n; +var maxUint64 = 2n ** 64n - 1n; +var maxUint72 = 2n ** 72n - 1n; +var maxUint80 = 2n ** 80n - 1n; +var maxUint88 = 2n ** 88n - 1n; +var maxUint96 = 2n ** 96n - 1n; +var maxUint104 = 2n ** 104n - 1n; +var maxUint112 = 2n ** 112n - 1n; +var maxUint120 = 2n ** 120n - 1n; +var maxUint128 = 2n ** 128n - 1n; +var maxUint136 = 2n ** 136n - 1n; +var maxUint144 = 2n ** 144n - 1n; +var maxUint152 = 2n ** 152n - 1n; +var maxUint160 = 2n ** 160n - 1n; +var maxUint168 = 2n ** 168n - 1n; +var maxUint176 = 2n ** 176n - 1n; +var maxUint184 = 2n ** 184n - 1n; +var maxUint192 = 2n ** 192n - 1n; +var maxUint200 = 2n ** 200n - 1n; +var maxUint208 = 2n ** 208n - 1n; +var maxUint216 = 2n ** 216n - 1n; +var maxUint224 = 2n ** 224n - 1n; +var maxUint232 = 2n ** 232n - 1n; +var maxUint240 = 2n ** 240n - 1n; +var maxUint248 = 2n ** 248n - 1n; +var maxUint256 = 2n ** 256n - 1n; + +// ../../node_modules/viem/_esm/utils/transaction/assertRequest.js +function assertRequest(args) { + const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (account && !isAddress(account.address)) + throw new InvalidAddressError({ address: account.address }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) + throw new FeeConflictError(); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} + +// ../../node_modules/viem/_esm/actions/public/call.js +async function call(client, args) { + const { account: account_ = client.account, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = "latest", accessList, blobs, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, ...rest } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (code && (factory || factoryData)) + throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); + if (code && to) + throw new BaseError2("Cannot provide both `code` & `to` as parameters."); + const deploylessCallViaBytecode = code && data_; + const deploylessCallViaFactory = factory && factoryData && to && data_; + const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; + const data = (() => { + if (deploylessCallViaBytecode) + return toDeploylessCallViaBytecodeData({ + code, + data: data_ + }); + if (deploylessCallViaFactory) + return toDeploylessCallViaFactoryData({ + data: data_, + factory, + factoryData, + to + }); + return data_; + })(); + try { + assertRequest(args); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + accessList, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: deploylessCall ? void 0 : to, + value + }); + if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { + try { + return await scheduleMulticall(client, { + ...request, + blockNumber, + blockTag + }); + } catch (err) { + if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) + throw err; + } + } + const response = await client.request({ + method: "eth_call", + params: rpcStateOverride ? [ + request, + block, + rpcStateOverride + ] : [request, block] + }); + if (response === "0x") + return { data: void 0 }; + return { data: response }; + } catch (err) { + const data2 = getRevertErrorData(err); + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-IAE5UWYX.js"); + if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to) + return { data: await offchainLookup2(client, { data: data2, to }) }; + if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") + throw new CounterfactualDeploymentFailedError({ factory }); + throw getCallError(err, { + ...args, + account, + chain: client.chain + }); + } +} +function shouldPerformMulticall({ request }) { + const { data, to, ...request_ } = request; + if (!data) + return false; + if (data.startsWith(aggregate3Signature)) + return false; + if (!to) + return false; + if (Object.values(request_).filter((x) => typeof x !== "undefined").length > 0) + return false; + return true; +} +async function scheduleMulticall(client, args) { + const { batchSize = 1024, wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to } = args; + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client.chain) + throw new ClientChainNotConfiguredError(); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" + }); + } + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const { schedule } = createBatchScheduler({ + id: `${client.uid}.${block}`, + wait, + shouldSplitBatch(args2) { + const size2 = args2.reduce((size3, { data: data2 }) => size3 + (data2.length - 2), 0); + return size2 > batchSize * 2; + }, + fn: async (requests) => { + const calls = requests.map((request) => ({ + allowFailure: true, + callData: request.data, + target: request.to + })); + const calldata = encodeFunctionData({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" + }); + const data2 = await client.request({ + method: "eth_call", + params: [ + { + data: calldata, + to: multicallAddress + }, + block + ] + }); + return decodeFunctionResult({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3", + data: data2 || "0x" + }); + } + }); + const [{ returnData, success }] = await schedule({ data, to }); + if (!success) + throw new RawContractError({ data: returnData }); + if (returnData === "0x") + return { data: void 0 }; + return { data: returnData }; +} +function toDeploylessCallViaBytecodeData(parameters) { + const { code, data } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(bytes, bytes)"]), + bytecode: deploylessCallViaBytecodeBytecode, + args: [code, data] + }); +} +function toDeploylessCallViaFactoryData(parameters) { + const { data, factory, factoryData, to } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(address, bytes, address, bytes)"]), + bytecode: deploylessCallViaFactoryBytecode, + args: [to, data, factory, factoryData] + }); +} +function getRevertErrorData(err) { + if (!(err instanceof BaseError2)) + return void 0; + const error = err.walk(); + return typeof error?.data === "object" ? error.data?.data : error.data; +} + +// ../../node_modules/viem/_esm/errors/ccip.js +var OffchainLookupError = class extends BaseError2 { + constructor({ callbackSelector, cause, data, extraData, sender, urls }) { + super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { + cause, + metaMessages: [ + ...cause.metaMessages || [], + cause.metaMessages?.length ? "" : [], + "Offchain Gateway Call:", + urls && [ + " Gateway URL(s):", + ...urls.map((url) => ` ${getUrl(url)}`) + ], + ` Sender: ${sender}`, + ` Data: ${data}`, + ` Callback selector: ${callbackSelector}`, + ` Extra data: ${extraData}` + ].flat(), + name: "OffchainLookupError" + }); + } +}; +var OffchainLookupResponseMalformedError = class extends BaseError2 { + constructor({ result, url }) { + super("Offchain gateway response is malformed. Response data must be a hex value.", { + metaMessages: [ + `Gateway URL: ${getUrl(url)}`, + `Response: ${stringify(result)}` + ], + name: "OffchainLookupResponseMalformedError" + }); + } +}; +var OffchainLookupSenderMismatchError = class extends BaseError2 { + constructor({ sender, to }) { + super("Reverted sender address does not match target contract address (`to`).", { + metaMessages: [ + `Contract address: ${to}`, + `OffchainLookup sender address: ${sender}` + ], + name: "OffchainLookupSenderMismatchError" + }); + } +}; + +// ../../node_modules/viem/_esm/utils/address/isAddressEqual.js +function isAddressEqual(a, b) { + if (!isAddress(a, { strict: false })) + throw new InvalidAddressError({ address: a }); + if (!isAddress(b, { strict: false })) + throw new InvalidAddressError({ address: b }); + return a.toLowerCase() === b.toLowerCase(); +} + +// ../../node_modules/viem/_esm/utils/ccip.js +var offchainLookupSignature = "0x556f1830"; +var offchainLookupAbiItem = { + name: "OffchainLookup", + type: "error", + inputs: [ + { + name: "sender", + type: "address" + }, + { + name: "urls", + type: "string[]" + }, + { + name: "callData", + type: "bytes" + }, + { + name: "callbackFunction", + type: "bytes4" + }, + { + name: "extraData", + type: "bytes" + } + ] +}; +async function offchainLookup(client, { blockNumber, blockTag, data, to }) { + const { args } = decodeErrorResult({ + data, + abi: [offchainLookupAbiItem] + }); + const [sender, urls, callData, callbackSelector, extraData] = args; + const { ccipRead } = client; + const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; + try { + if (!isAddressEqual(to, sender)) + throw new OffchainLookupSenderMismatchError({ sender, to }); + const result = await ccipRequest_({ data: callData, sender, urls }); + const { data: data_ } = await call(client, { + blockNumber, + blockTag, + data: concat([ + callbackSelector, + encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) + ]), + to + }); + return data_; + } catch (err) { + throw new OffchainLookupError({ + callbackSelector, + cause: err, + data, + extraData, + sender, + urls + }); + } +} +async function ccipRequest({ data, sender, urls }) { + let error = new Error("An unknown error occurred."); + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + const method = url.includes("{data}") ? "GET" : "POST"; + const body = method === "POST" ? { data, sender } : void 0; + const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; + try { + const response = await fetch(url.replace("{sender}", sender).replace("{data}", data), { + body: JSON.stringify(body), + headers, + method + }); + let result; + if (response.headers.get("Content-Type")?.startsWith("application/json")) { + result = (await response.json()).data; + } else { + result = await response.text(); + } + if (!response.ok) { + error = new HttpRequestError({ + body, + details: result?.error ? stringify(result.error) : response.statusText, + headers: response.headers, + status: response.status, + url + }); + continue; + } + if (!isHex(result)) { + error = new OffchainLookupResponseMalformedError({ + result, + url + }); + continue; + } + return result; + } catch (err) { + error = new HttpRequestError({ + body, + details: err.message, + url + }); + } + } + throw error; +} + +export { + aexists, + aoutput, + createView, + rotr, + toBytes2 as toBytes, + Hash, + wrapConstructor, + BaseError2 as BaseError, + isHex, + size, + trim, + toBytes as toBytes2, + hexToBytes, + hexToBigInt, + hexToNumber, + toHex, + bytesToHex, + numberToHex, + stringToHex, + InvalidAddressError, + keccak256, + checksumAddress, + isAddress, + concat, + concatHex, + createCursor, + InvalidLegacyVError, + InvalidSerializableTransactionError, + InvalidStorageKeySizeError, + maxUint256, + InvalidChainIdError, + FeeCapTooHighError, + TipAboveFeeCapError, + slice, + BytesSizeMismatchError, + bytesRegex2 as bytesRegex, + integerRegex2 as integerRegex, + encodeAbiParameters, + stringify, + offchainLookupSignature, + offchainLookupAbiItem, + offchainLookup, + ccipRequest +}; +/*! Bundled license information: + +@noble/hashes/esm/utils.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) +*/ +//# sourceMappingURL=chunk-KSHJJL6X.js.map \ No newline at end of file diff --git a/dist/chunk-KSHJJL6X.js.map b/dist/chunk-KSHJJL6X.js.map new file mode 100644 index 0000000..7f6eac6 --- /dev/null +++ b/dist/chunk-KSHJJL6X.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/abitype/src/version.ts","../../../node_modules/abitype/src/errors.ts","../../../node_modules/abitype/src/regex.ts","../../../node_modules/abitype/src/human-readable/formatAbiParameter.ts","../../../node_modules/abitype/src/human-readable/formatAbiParameters.ts","../../../node_modules/abitype/src/human-readable/formatAbiItem.ts","../../../node_modules/abitype/src/human-readable/runtime/signatures.ts","../../../node_modules/abitype/src/human-readable/errors/abiItem.ts","../../../node_modules/abitype/src/human-readable/errors/abiParameter.ts","../../../node_modules/abitype/src/human-readable/errors/signature.ts","../../../node_modules/abitype/src/human-readable/errors/struct.ts","../../../node_modules/abitype/src/human-readable/errors/splitParameters.ts","../../../node_modules/abitype/src/human-readable/runtime/cache.ts","../../../node_modules/abitype/src/human-readable/runtime/utils.ts","../../../node_modules/abitype/src/human-readable/runtime/structs.ts","../../../node_modules/abitype/src/human-readable/parseAbi.ts","../../../node_modules/viem/accounts/utils/parseAccount.ts","../../../node_modules/viem/constants/abis.ts","../../../node_modules/viem/constants/contract.ts","../../../node_modules/viem/constants/contracts.ts","../../../node_modules/viem/errors/version.ts","../../../node_modules/viem/errors/base.ts","../../../node_modules/viem/errors/chain.ts","../../../node_modules/viem/constants/solidity.ts","../../../node_modules/viem/utils/abi/formatAbiItem.ts","../../../node_modules/viem/utils/data/isHex.ts","../../../node_modules/viem/utils/data/size.ts","../../../node_modules/viem/errors/abi.ts","../../../node_modules/viem/errors/data.ts","../../../node_modules/viem/utils/data/slice.ts","../../../node_modules/viem/utils/data/pad.ts","../../../node_modules/viem/errors/encoding.ts","../../../node_modules/viem/utils/data/trim.ts","../../../node_modules/viem/utils/encoding/fromHex.ts","../../../node_modules/viem/utils/encoding/toHex.ts","../../../node_modules/viem/utils/encoding/toBytes.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/viem/utils/hash/keccak256.ts","../../../node_modules/viem/utils/hash/hashSignature.ts","../../../node_modules/viem/utils/hash/normalizeSignature.ts","../../../node_modules/viem/utils/hash/toSignature.ts","../../../node_modules/viem/utils/hash/toSignatureHash.ts","../../../node_modules/viem/utils/hash/toFunctionSelector.ts","../../../node_modules/viem/errors/address.ts","../../../node_modules/viem/utils/lru.ts","../../../node_modules/viem/utils/address/isAddress.ts","../../../node_modules/viem/utils/address/getAddress.ts","../../../node_modules/viem/errors/cursor.ts","../../../node_modules/viem/utils/cursor.ts","../../../node_modules/viem/utils/encoding/fromBytes.ts","../../../node_modules/viem/utils/data/concat.ts","../../../node_modules/viem/utils/regex.ts","../../../node_modules/viem/utils/abi/encodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeErrorResult.ts","../../../node_modules/viem/utils/stringify.ts","../../../node_modules/viem/utils/hash/toEventSelector.ts","../../../node_modules/viem/utils/abi/getAbiItem.ts","../../../node_modules/viem/constants/unit.ts","../../../node_modules/viem/utils/unit/formatUnits.ts","../../../node_modules/viem/utils/unit/formatEther.ts","../../../node_modules/viem/utils/unit/formatGwei.ts","../../../node_modules/viem/errors/stateOverride.ts","../../../node_modules/viem/errors/transaction.ts","../../../node_modules/viem/errors/utils.ts","../../../node_modules/viem/errors/contract.ts","../../../node_modules/viem/utils/abi/decodeFunctionResult.ts","../../../node_modules/viem/utils/abi/encodeDeployData.ts","../../../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../../../node_modules/viem/utils/abi/encodeFunctionData.ts","../../../node_modules/viem/utils/chain/getChainContractAddress.ts","../../../node_modules/viem/errors/node.ts","../../../node_modules/viem/errors/request.ts","../../../node_modules/viem/utils/errors/getNodeError.ts","../../../node_modules/viem/utils/errors/getCallError.ts","../../../node_modules/viem/utils/formatters/extract.ts","../../../node_modules/viem/utils/formatters/transactionRequest.ts","../../../node_modules/viem/utils/promise/withResolvers.ts","../../../node_modules/viem/utils/promise/createBatchScheduler.ts","../../../node_modules/viem/utils/stateOverride.ts","../../../node_modules/viem/constants/number.ts","../../../node_modules/viem/utils/transaction/assertRequest.ts","../../../node_modules/viem/actions/public/call.ts","../../../node_modules/viem/errors/ccip.ts","../../../node_modules/viem/utils/address/isAddressEqual.ts","../../../node_modules/viem/utils/ccip.ts"],"sourcesContent":["export const version = '1.0.7'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n\n override name = 'AbiTypeError'\n\n constructor(shortMessage: string, args: BaseErrorArgs = {}) {\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 const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: abitype@${version}`,\n ].join('\\n')\n\n super(message)\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","// 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 type | 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 abiParameter - 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 abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter 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 [key in keyof components]: FormatAbiParameter<\n {\n type: components[key]['type']\n } & (IsNarrowable extends true\n ? { name: components[key]['name'] }\n : unknown) &\n (components[key] extends { components: readonly AbiParameter[] }\n ? { components: components[key]['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 : `${abiParameter['type']}${abiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${abiParameter['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 abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): 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 abiParameters - 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [key in keyof abiParameters]: 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: abiParameters): 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 {\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 abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem =\n Abi[number] extends abiItem\n ? string\n :\n | (abiItem extends AbiFunction\n ? AbiFunction extends abiItem\n ? string\n : `function ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${abiItem['stateMutability']}`\n : ''}${abiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters})`}`\n : never)\n | (abiItem extends AbiEvent\n ? AbiEvent extends abiItem\n ? string\n : `event ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiError\n ? AbiError extends abiItem\n ? string\n : `error ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiConstructor\n ? AbiConstructor extends abiItem\n ? string\n : `constructor(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiFallback\n ? AbiFallback extends abiItem\n ? string\n : `fallback() external${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiReceive\n ? AbiReceive extends abiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? abiParameters\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: abiItem,\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 if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n if (abiItem.type === 'fallback')\n return `fallback() external${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }` as Result\n return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n EventModifier,\n FunctionModifier,\n Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n errorSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isEventSignature(signature: string) {\n return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n eventSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n return execTyped<{\n name: string\n parameters: string\n stateMutability?: AbiStateMutability\n returns?: string\n }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?.*?)\\}$/\nexport function isStructSignature(signature: string) {\n return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n return execTyped<{ name: string; properties: string }>(\n structSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n /^constructor\\((?.*?)\\)(?:\\s(?payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex =\n /^fallback\\(\\) external(?:\\s(?payable{1}))?$/\nexport function isFallbackSignature(signature: string) {\n return fallbackSignatureRegex.test(signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set([\n 'memory',\n 'indexed',\n 'storage',\n 'calldata',\n])\nexport const eventModifiers = new Set(['indexed'])\nexport const functionModifiers = new Set([\n 'calldata',\n 'memory',\n 'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n override name = 'InvalidAbiItemError'\n\n constructor({ signature }: { signature: string | object }) {\n super('Failed to parse ABI item.', {\n details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n docsPath: '/api/human#parseabiitem-1',\n })\n }\n}\n\nexport class UnknownTypeError extends BaseError {\n override name = 'UnknownTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [\n `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n ],\n })\n }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n override name = 'UnknownSolidityTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n override name = 'InvalidAbiParameterError'\n\n constructor({ param }: { param: string | object }) {\n super('Failed to parse ABI parameter.', {\n details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n docsPath: '/api/human#parseabiparameter-1',\n })\n }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n override name = 'InvalidAbiParametersError'\n\n constructor({ params }: { params: string | object }) {\n super('Failed to parse ABI parameters.', {\n details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n docsPath: '/api/human#parseabiparameters-1',\n })\n }\n}\n\nexport class InvalidParameterError extends BaseError {\n override name = 'InvalidParameterError'\n\n constructor({ param }: { param: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n })\n }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n override name = 'SolidityProtectedKeywordError'\n\n constructor({ param, name }: { param: string; name: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n ],\n })\n }\n}\n\nexport class InvalidModifierError extends BaseError {\n override name = 'InvalidModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n ],\n })\n }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n override name = 'InvalidFunctionModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n ],\n })\n }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n override name = 'InvalidAbiTypeParameterError'\n\n constructor({\n abiParameter,\n }: {\n abiParameter: AbiParameter & { indexed?: boolean | undefined }\n }) {\n super('Invalid ABI parameter.', {\n details: JSON.stringify(abiParameter, null, 2),\n metaMessages: ['ABI parameter type is invalid.'],\n })\n }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n override name = 'InvalidSignatureError'\n\n constructor({\n signature,\n type,\n }: {\n signature: string\n type: AbiItemType | 'struct'\n }) {\n super(`Invalid ${type} signature.`, {\n details: signature,\n })\n }\n}\n\nexport class UnknownSignatureError extends BaseError {\n override name = 'UnknownSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Unknown signature.', {\n details: signature,\n })\n }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n override name = 'InvalidStructSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Invalid struct signature.', {\n details: signature,\n metaMessages: ['No properties exist.'],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n override name = 'CircularReferenceError'\n\n constructor({ type }: { type: string }) {\n super('Circular reference detected.', {\n metaMessages: [`Struct \"${type}\" is a circular reference.`],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n override name = 'InvalidParenthesisError'\n\n constructor({ current, depth }: { current: string; depth: number }) {\n super('Unbalanced parentheses.', {\n metaMessages: [\n `\"${current.trim()}\" has too many ${\n depth > 0 ? 'opening' : 'closing'\n } parentheses.`,\n ],\n details: `Depth \"${depth}\"`,\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport type { StructLookup } from '../types/structs.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n param: string,\n type?: AbiItemType | 'struct',\n structs?: StructLookup,\n) {\n let structKey = ''\n if (structs)\n for (const struct of Object.entries(structs)) {\n if (!struct) continue\n let propertyKey = ''\n for (const property of struct[1]) {\n propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`\n }\n structKey += `(${struct[0]}{${propertyKey}})`\n }\n if (type) return `${type}:${param}${structKey}`\n return param\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n string,\n AbiParameter & { indexed?: boolean }\n>([\n // Unnamed\n ['address', { type: 'address' }],\n ['bool', { type: 'bool' }],\n ['bytes', { type: 'bytes' }],\n ['bytes32', { type: 'bytes32' }],\n ['int', { type: 'int256' }],\n ['int256', { type: 'int256' }],\n ['string', { type: 'string' }],\n ['uint', { type: 'uint256' }],\n ['uint8', { type: 'uint8' }],\n ['uint16', { type: 'uint16' }],\n ['uint24', { type: 'uint24' }],\n ['uint32', { type: 'uint32' }],\n ['uint64', { type: 'uint64' }],\n ['uint96', { type: 'uint96' }],\n ['uint112', { type: 'uint112' }],\n ['uint160', { type: 'uint160' }],\n ['uint192', { type: 'uint192' }],\n ['uint256', { type: 'uint256' }],\n\n // Named\n ['address owner', { type: 'address', name: 'owner' }],\n ['address to', { type: 'address', name: 'to' }],\n ['bool approved', { type: 'bool', name: 'approved' }],\n ['bytes _data', { type: 'bytes', name: '_data' }],\n ['bytes data', { type: 'bytes', name: 'data' }],\n ['bytes signature', { type: 'bytes', name: 'signature' }],\n ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n ['bytes32 r', { type: 'bytes32', name: 'r' }],\n ['bytes32 root', { type: 'bytes32', name: 'root' }],\n ['bytes32 s', { type: 'bytes32', name: 's' }],\n ['string name', { type: 'string', name: 'name' }],\n ['string symbol', { type: 'string', name: 'symbol' }],\n ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint8 v', { type: 'uint8', name: 'v' }],\n ['uint256 balance', { type: 'uint256', name: 'balance' }],\n ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint256 value', { type: 'uint256', name: 'value' }],\n\n // Indexed\n [\n 'event:address indexed from',\n { type: 'address', name: 'from', indexed: true },\n ],\n ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n [\n 'event:uint indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n [\n 'event:uint256 indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n])\n","import type {\n AbiItemType,\n AbiType,\n SolidityArray,\n SolidityBytes,\n SolidityString,\n SolidityTuple,\n} from '../../abi.js'\nimport {\n bytesRegex,\n execTyped,\n integerRegex,\n isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n eventModifiers,\n execConstructorSignature,\n execErrorSignature,\n execEventSignature,\n execFunctionSignature,\n functionModifiers,\n isConstructorSignature,\n isErrorSignature,\n isEventSignature,\n isFallbackSignature,\n isFunctionSignature,\n isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n if (isFunctionSignature(signature)) {\n const match = execFunctionSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n const inputParams = splitParameters(match.parameters)\n const inputs = []\n const inputLength = inputParams.length\n for (let i = 0; i < inputLength; i++) {\n inputs.push(\n parseAbiParameter(inputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n\n const outputs = []\n if (match.returns) {\n const outputParams = splitParameters(match.returns)\n const outputLength = outputParams.length\n for (let i = 0; i < outputLength; i++) {\n outputs.push(\n parseAbiParameter(outputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n }\n\n return {\n name: match.name,\n type: 'function',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs,\n outputs,\n }\n }\n\n if (isEventSignature(signature)) {\n const match = execEventSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, {\n modifiers: eventModifiers,\n structs,\n type: 'event',\n }),\n )\n }\n return { name: match.name, type: 'event', inputs: abiParameters }\n }\n\n if (isErrorSignature(signature)) {\n const match = execErrorSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'error' }),\n )\n }\n return { name: match.name, type: 'error', inputs: abiParameters }\n }\n\n if (isConstructorSignature(signature)) {\n const match = execConstructorSignature(signature)\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n )\n }\n return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n }\n\n if (isFallbackSignature(signature)) return { type: 'fallback' }\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n /^\\((?.+?)\\)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n modifiers?: Set\n structs?: StructLookup\n type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n // optional namespace cache by `type`\n const parameterCacheKey = getParameterCacheKey(\n param,\n options?.type,\n options?.structs,\n )\n if (parameterCache.has(parameterCacheKey))\n return parameterCache.get(parameterCacheKey)!\n\n const isTuple = isTupleRegex.test(param)\n const match = execTyped<{\n array?: string\n modifier?: Modifier\n name?: string\n type: string\n }>(\n isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n param,\n )\n if (!match) throw new InvalidParameterError({ param })\n\n if (match.name && isSolidityKeyword(match.name))\n throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n const name = match.name ? { name: match.name } : {}\n const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n const structs = options?.structs ?? {}\n let type: string\n let components = {}\n if (isTuple) {\n type = 'tuple'\n const params = splitParameters(match.type)\n const components_ = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n // remove `modifiers` from `options` to prevent from being added to tuple components\n components_.push(parseAbiParameter(params[i]!, { structs }))\n }\n components = { components: components_ }\n } else if (match.type in structs) {\n type = 'tuple'\n components = { components: structs[match.type] }\n } else if (dynamicIntegerRegex.test(match.type)) {\n type = `${match.type}256`\n } else {\n type = match.type\n if (!(options?.type === 'struct') && !isSolidityType(type))\n throw new UnknownSolidityTypeError({ type })\n }\n\n if (match.modifier) {\n // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n if (!options?.modifiers?.has?.(match.modifier))\n throw new InvalidModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n\n // Check if resolved `type` is valid if there is a function modifier\n if (\n functionModifiers.has(match.modifier as FunctionModifier) &&\n !isValidDataLocation(type, !!match.array)\n )\n throw new InvalidFunctionModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n }\n\n const abiParameter = {\n type: `${type}${match.array ?? ''}`,\n ...name,\n ...indexed,\n ...components,\n }\n parameterCache.set(parameterCacheKey, abiParameter)\n return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n params: string,\n result: string[] = [],\n current = '',\n depth = 0,\n): readonly string[] {\n const length = params.trim().length\n // biome-ignore lint/correctness/noUnreachable: recursive\n for (let i = 0; i < length; i++) {\n const char = params[i]\n const tail = params.slice(i + 1)\n switch (char) {\n case ',':\n return depth === 0\n ? splitParameters(tail, [...result, current.trim()])\n : splitParameters(tail, result, `${current}${char}`, depth)\n case '(':\n return splitParameters(tail, result, `${current}${char}`, depth + 1)\n case ')':\n return splitParameters(tail, result, `${current}${char}`, depth - 1)\n default:\n return splitParameters(tail, result, `${current}${char}`, depth)\n }\n }\n\n if (current === '') return result\n if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n result.push(current.trim())\n return result\n}\n\nexport function isSolidityType(\n type: string,\n): type is Exclude {\n return (\n type === 'address' ||\n type === 'bool' ||\n type === 'function' ||\n type === 'string' ||\n bytesRegex.test(type) ||\n integerRegex.test(type)\n )\n}\n\nconst protectedKeywordsRegex =\n /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\n/** @internal */\nexport function isSolidityKeyword(name: string) {\n return (\n name === 'address' ||\n name === 'bool' ||\n name === 'function' ||\n name === 'string' ||\n name === 'tuple' ||\n bytesRegex.test(name) ||\n integerRegex.test(name) ||\n protectedKeywordsRegex.test(name)\n )\n}\n\n/** @internal */\nexport function isValidDataLocation(\n type: string,\n isArray: boolean,\n): type is Exclude<\n AbiType,\n SolidityString | Extract | SolidityArray\n> {\n return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n const shallowStructs: StructLookup = {}\n const signaturesLength = signatures.length\n for (let i = 0; i < signaturesLength; i++) {\n const signature = signatures[i]!\n if (!isStructSignature(signature)) continue\n\n const match = execStructSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n const properties = match.properties.split(';')\n\n const components: AbiParameter[] = []\n const propertiesLength = properties.length\n for (let k = 0; k < propertiesLength; k++) {\n const property = properties[k]!\n const trimmed = property.trim()\n if (!trimmed) continue\n const abiParameter = parseAbiParameter(trimmed, {\n type: 'struct',\n })\n components.push(abiParameter)\n }\n\n if (!components.length) throw new InvalidStructSignatureError({ signature })\n shallowStructs[match.name] = components\n }\n\n // Resolve nested structs inside each parameter\n const resolvedStructs: StructLookup = {}\n const entries = Object.entries(shallowStructs)\n const entriesLength = entries.length\n for (let i = 0; i < entriesLength; i++) {\n const [name, parameters] = entries[i]!\n resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n }\n\n return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n abiParameters: readonly (AbiParameter & { indexed?: true })[],\n structs: StructLookup,\n ancestors = new Set(),\n) {\n const components: AbiParameter[] = []\n const length = abiParameters.length\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i]!\n const isTuple = isTupleRegex.test(abiParameter.type)\n if (isTuple) components.push(abiParameter)\n else {\n const match = execTyped<{ array?: string; type: string }>(\n typeWithoutTupleRegex,\n abiParameter.type,\n )\n if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n const { array, type } = match\n if (type in structs) {\n if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n components.push({\n ...abiParameter,\n type: `tuple${array ?? ''}`,\n components: resolveStructs(\n structs[type] ?? [],\n structs,\n new Set([...ancestors, type]),\n ),\n })\n } else {\n if (isSolidityType(type)) components.push(abiParameter)\n else throw new UnknownTypeError({ type })\n }\n }\n }\n\n return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Error, Filter } from '../types.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * type Result = ParseAbi<\n * // ^? type Result = readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * [\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ]\n * >\n */\nexport type ParseAbi =\n string[] extends signatures\n ? Abi // If `T` was not able to be inferred (e.g. just `string[]`), return `Abi`\n : signatures extends readonly string[]\n ? signatures extends Signatures // Validate signatures\n ? ParseStructs extends infer sructs\n ? {\n [key in keyof signatures]: signatures[key] extends string\n ? ParseSignature\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends infer result\n ? result extends readonly []\n ? never\n : result\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n * // ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi(\n signatures: signatures['length'] extends 0\n ? Error<'At least one signature required'>\n : Signatures extends signatures\n ? signatures\n : Signatures,\n): ParseAbi {\n const structs = parseStructs(signatures as readonly string[])\n const abi = []\n const length = signatures.length as number\n for (let i = 0; i < length; i++) {\n const signature = (signatures as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n abi.push(parseSignature(signature, structs))\n }\n return abi as unknown as ParseAbi\n}\n","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(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\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 {\n inputs: [],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n components: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'errors',\n type: 'tuple[]',\n },\n ],\n name: 'HttpError',\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 {\n name: 'resolve',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n { name: 'gateways', type: 'string[]' },\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 {\n name: 'reverse',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'string[]', name: 'gateways' },\n ],\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\n/** @internal */\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 name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n] as const\n\n/** [ERC-20 Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) */\nexport const erc20Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/**\n * [bytes32-flavored ERC-20](https://docs.makerdao.com/smart-contract-modules/mkr-module#4.-gotchas-potential-source-of-user-error)\n * for tokens (ie. Maker) that use bytes32 instead of string.\n */\nexport const erc20Abi_bytes32 = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/** [ERC-721 Non-Fungible Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) */\nexport const erc721Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'ApprovalForAll',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n name: 'approved',\n type: 'bool',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'getApproved',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'isApprovedForAll',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'operator',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'ownerOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'id',\n type: 'uint256',\n },\n {\n name: 'data',\n type: 'bytes',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'setApprovalForAll',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'operator',\n type: 'address',\n },\n {\n name: 'approved',\n type: 'bool',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenURI',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'tokeId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n] as const\n\n/** [ERC-4626 Tokenized Vaults Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-4626) */\nexport const erc4626Abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Deposit',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n name: 'allowance',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'approve',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'asset',\n outputs: [\n {\n name: 'assetTokenAddress',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'convertToAssets',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'convertToShares',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'deposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxDeposit',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxMint',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxRedeem',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxWithdraw',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'mint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewDeposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewMint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewRedeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewWithdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'redeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalAssets',\n outputs: [\n {\n name: 'totalManagedAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transfer',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transferFrom',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'withdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","export const aggregate3Signature = '0x82ad56cb'\n","export const deploylessCallViaBytecodeBytecode =\n '0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe'\n\nexport const deploylessCallViaFactoryBytecode =\n '0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe'\n\nexport const universalSignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n","export const version = '2.21.58'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\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(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (\n err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined\n )\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 constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint | undefined\n chain: Chain\n contract: { name: string; blockCreated?: number | undefined }\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 name: 'ChainDoesNotSupportContract',\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\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 name: 'ChainMismatchError',\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\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 name: 'ChainNotFoundError',\n },\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n })\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n { name: 'InvalidChainIdError' },\n )\n }\n}\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: 'Arithmetic 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","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 | undefined } = {},\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 | undefined } = {},\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 { 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 | undefined } = {},\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 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 type { Abi, 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 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 name: 'AbiConstructorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\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 name: 'AbiConstructorParamsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\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 {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\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 name: 'AbiDecodingDataSizeTooSmallError',\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 constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n })\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingArrayLengthMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\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 { name: 'AbiEncodingBytesSizeMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingLengthMismatchError' },\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\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 name: 'AbiErrorInputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(\n errorName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiErrorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\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 name: 'AbiErrorSignatureNotFoundError',\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\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 name: 'AbiEventSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(\n eventName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiEventNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(\n functionName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiFunctionNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\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 name: 'AbiFunctionOutputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\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 name: 'AbiFunctionSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(\n x: { abiItem: Abi[number]; type: string },\n y: { abiItem: Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n })\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n })\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\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 name: 'DecodeLogDataMismatch',\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 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 { name: 'DecodeLogTopicsMismatch' },\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\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, name: 'InvalidAbiEncodingType' },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\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, name: 'InvalidAbiDecodingType' },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n })\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\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 { name: 'InvalidDefinitionTypeError' },\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\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 { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\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 { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\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()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\n )\n }\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 = value 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: value,\n start?: number | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined) {\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(\n value: Hex | ByteArray,\n start?: number | undefined,\n end?: number | undefined,\n) {\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 {\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' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: value,\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 { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\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 { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\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 name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\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 { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim(\n hexOrBytes: value,\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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to 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\n * - Example: https://viem.sh/docs/utilities/fromHex#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 to 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 | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 | undefined\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#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#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 | undefined\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#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 {\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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toHex#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 | undefined\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#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 | undefined\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#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 | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\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#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: bigint | number | undefined\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${(\n signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : 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 | undefined\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#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 { 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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toBytes#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 | undefined\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#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 | undefined\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#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#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(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\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#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","function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n// TODO: re-check https://issues.chromium.org/issues/42212588\n\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { abytes, aexists, anumber, aoutput } 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 isLE,\n byteSwap32,\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: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: 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 anumber(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 if (!isLE) byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE) byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input) {\n aexists(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 aexists(this, false);\n abytes(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 anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array) {\n aoutput(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 | (to extends 'bytes' ? ByteArray : never)\n | (to 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_?: to | undefined,\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 ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport function hashSignature(sig: string) {\n return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype 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 AbiEvent, 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 ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n const def_ = (() => {\n if (typeof def === 'string') return def\n return formatAbiItem(def)\n })()\n return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n | HashSignatureErrorType\n | ToSignatureErrorType\n | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n return hashSignature(toSignature(fn))\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToFunctionSelectorErrorType =\n | ToSignatureHashErrorType\n | SliceErrorType\n | ErrorType\n\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn: string | AbiFunction) =>\n slice(toSignatureHash(fn), 0, 4)\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\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 { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap
(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\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 const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n })\n }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n { name: 'PositionOutOfBoundsError' },\n )\n }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n RecursiveReadLimitExceededError & {\n name: 'RecursiveReadLimitExceededError'\n }\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n { name: 'RecursiveReadLimitExceededError' },\n )\n }\n}\n","import {\n NegativeOffsetError,\n type NegativeOffsetErrorType,\n PositionOutOfBoundsError,\n type PositionOutOfBoundsErrorType,\n RecursiveReadLimitExceededError,\n type RecursiveReadLimitExceededErrorType,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n bytes: ByteArray\n dataView: DataView\n position: number\n positionReadCount: Map\n recursiveReadCount: number\n recursiveReadLimit: number\n remaining: number\n assertReadLimit(position?: number): void\n assertPosition(position: number): void\n decrementPosition(offset: number): void\n getReadCount(position?: number): number\n incrementPosition(offset: number): void\n inspectByte(position?: number): ByteArray[number]\n inspectBytes(length: number, position?: number): ByteArray\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: ByteArray[number]): void\n pushBytes(bytes: ByteArray): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): ByteArray[number]\n readBytes(length: number, size?: number): ByteArray\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\n\ntype CursorErrorType =\n | CursorAssertPositionErrorType\n | CursorDecrementPositionErrorType\n | CursorIncrementPositionErrorType\n | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype StaticCursorErrorType =\n | NegativeOffsetErrorType\n | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n })\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n })\n },\n decrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position - offset\n this.assertPosition(position)\n this.position = position\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0\n },\n incrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position + offset\n this.assertPosition(position)\n this.position = position\n },\n inspectByte(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + length - 1)\n return this.bytes.subarray(position, position + length)\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 1)\n return this.dataView.getUint16(position)\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 2)\n return (\n (this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2)\n )\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 3)\n return this.dataView.getUint32(position)\n },\n pushByte(byte: ByteArray[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: ByteArray) {\n this.assertPosition(this.position + bytes.length - 1)\n this.bytes.set(bytes, this.position)\n this.position += bytes.length\n },\n pushUint8(value: number) {\n this.assertPosition(this.position)\n this.bytes[this.position] = value\n this.position++\n },\n pushUint16(value: number) {\n this.assertPosition(this.position + 1)\n this.dataView.setUint16(this.position, value)\n this.position += 2\n },\n pushUint24(value: number) {\n this.assertPosition(this.position + 2)\n this.dataView.setUint16(this.position, value >> 8)\n this.dataView.setUint8(this.position + 2, value & ~4294967040)\n this.position += 3\n },\n pushUint32(value: number) {\n this.assertPosition(this.position + 3)\n this.dataView.setUint32(this.position, value)\n this.position += 4\n },\n readByte() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectByte()\n this.position++\n return value\n },\n readBytes(length, size) {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectBytes(length)\n this.position += size ?? length\n return value\n },\n readUint8() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint8()\n this.position += 1\n return value\n },\n readUint16() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint16()\n this.position += 2\n return value\n },\n readUint24() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint24()\n this.position += 3\n return value\n },\n readUint32() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint32()\n this.position += 4\n return value\n },\n get remaining() {\n return this.bytes.length - this.position\n },\n setPosition(position) {\n const oldPosition = this.position\n this.assertPosition(position)\n this.position = position\n return () => (this.position = oldPosition)\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n const count = this.getReadCount()\n this.positionReadCount.set(this.position, count + 1)\n if (count > 0) this.recursiveReadCount++\n },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n | CursorErrorType\n | StaticCursorErrorType\n | ErrorType\n\nexport function createCursor(\n bytes: ByteArray,\n { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n type AssertSizeErrorType,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n assertSize,\n hexToBigInt,\n hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n | to\n | {\n /** Size of the bytes. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromBytesReturnType = to extends 'string'\n ? string\n : to extends 'hex'\n ? Hex\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromBytesErrorType =\n | BytesToHexErrorType\n | BytesToBigIntErrorType\n | BytesToBoolErrorType\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n bytes: ByteArray,\n toOrOpts: FromBytesParameters,\n): FromBytesReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number')\n return bytesToNumber(bytes, opts) as FromBytesReturnType\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts) as FromBytesReturnType\n if (to === 'boolean')\n return bytesToBool(bytes, opts) as FromBytesReturnType\n if (to === 'string')\n return bytesToString(bytes, opts) as FromBytesReturnType\n return bytesToHex(bytes, opts) as FromBytesReturnType\n}\n\nexport type BytesToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n | BytesToHexErrorType\n | HexToBigIntErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n bytes: ByteArray,\n opts: BytesToBigIntOpts = {},\n): bigint {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n bytes_: ByteArray,\n opts: BytesToBoolOpts = {},\n): boolean {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes)\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes)\n return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n | BytesToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n bytes: ByteArray,\n opts: BytesToNumberOpts = {},\n): number {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n bytes_: ByteArray,\n opts: BytesToStringOpts = {},\n): string {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat(\n values: readonly value[],\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","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\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","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 { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.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'\nimport { integerRegex } from '../regex.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 *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: params,\n values: params 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 as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values: values as any,\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\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams({\n params,\n values,\n}: {\n params: params\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\ntype PrepareParamErrorType =\n | EncodeAddressErrorType\n | EncodeArrayErrorType\n | EncodeBytesErrorType\n | EncodeBoolErrorType\n | EncodeNumberErrorType\n | EncodeStringErrorType\n | EncodeTupleErrorType\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam({\n param,\n value,\n}: {\n param: param\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 const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\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\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | 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\ntype 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\ntype EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray(\n value: AbiParameterToPrimitiveType,\n {\n length,\n param,\n }: {\n length: number | null\n param: param\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\ntype EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes(\n value: Hex,\n { param }: { param: param },\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 !== Number.parseInt(paramSize))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n if (typeof value !== 'boolean')\n throw new BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\ntype 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\ntype EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType,\n { param }: { param: param },\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\ntype 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 { AbiParameter, AbiParametersToPrimitiveTypes } from 'abitype'\n\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type BytesToBigIntErrorType,\n type BytesToBoolErrorType,\n type BytesToNumberErrorType,\n type BytesToStringErrorType,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n params extends readonly AbiParameter[] ? params : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | DecodeParameterErrorType\n | SizeErrorType\n | CreateCursorErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const params extends readonly AbiParameter[],\n>(\n params: params,\n data: ByteArray | Hex,\n): DecodeAbiParametersReturnType {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data\n const cursor = createCursor(bytes)\n\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n\n let consumed = 0\n const values = []\n for (let i = 0; i < params.length; ++i) {\n const param = params[i]\n cursor.setPosition(consumed)\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n })\n consumed += consumed_\n values.push(data)\n }\n return values as DecodeAbiParametersReturnType\n}\n\ntype DecodeParameterErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeStringErrorType\n | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n if (param.type === 'address') return decodeAddress(cursor)\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | BytesToHexErrorType\n | SliceBytesErrorType\n | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n const value = cursor.readBytes(32)\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n cursor: Cursor,\n param: AbiParameter,\n { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 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 // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n | BytesToNumberErrorType\n | BytesToHexErrorType\n | ErrorType\n\nfunction decodeBytes(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [bytesToHex(data), 32]\n }\n\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size), 32))\n return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n | BytesToNumberErrorType\n | BytesToBigIntErrorType\n | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256')\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n cursor: Cursor,\n param: TupleAbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\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 // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\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 [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(\n cursor: Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = bytesToString(trim(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\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 } 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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n ContractErrorArgs,\n ContractErrorName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { slice } from '../data/slice.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = { abi?: abi | undefined; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allErrorNames extends ContractErrorName = ContractErrorName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [errorName in allErrorNames]: {\n abiItem: abi extends Abi\n ? Abi extends abi\n ? AbiItem\n : ExtractAbiError\n : AbiItem\n args: ContractErrorArgs\n errorName: errorName\n }\n }[allErrorNames]\n >\n : {\n abiItem: AbiItem\n args: readonly unknown[] | undefined\n errorName: string\n }\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult(\n parameters: DecodeErrorResultParameters,\n): DecodeErrorResultReturnType {\n const { abi, data } = parameters as DecodeErrorResultParameters\n\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...(abi || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args:\n 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType\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 type { ErrorType } from '../../errors/utils.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport {\n AbiItemAmbiguityError,\n type AbiItemAmbiguityErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ExtractAbiItemForArgs,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nexport type GetAbiItemParameters<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n ///\n allArgs = AbiItemArgs,\n allNames = AbiItemName,\n> = {\n abi: abi\n name:\n | allNames // show all options\n | (name extends allNames ? name : never) // infer value\n | Hex // function selector\n} & UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | ToFunctionSelectorErrorType\n | AbiItemAmbiguityErrorType\n | ErrorType\n\nexport type GetAbiItemReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n> = abi extends Abi\n ? Abi extends abi\n ? AbiItem | undefined\n : ExtractAbiItemForArgs<\n abi,\n name,\n args extends AbiItemArgs ? args : AbiItemArgs\n >\n : AbiItem | undefined\n\nexport function getAbiItem<\n const abi extends Abi | readonly unknown[],\n name extends AbiItemName,\n const args extends AbiItemArgs | undefined = undefined,\n>(\n parameters: GetAbiItemParameters,\n): GetAbiItemReturnType {\n const { abi, args = [], name } = parameters as unknown as GetAbiItemParameters\n\n const isSelector = isHex(name, { strict: false })\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return toEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0)\n return undefined as GetAbiItemReturnType\n if (abiItems.length === 1)\n return abiItems[0] as GetAbiItemReturnType\n\n let matchedAbiItem: AbiItem | undefined = undefined\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)\n return abiItem as GetAbiItemReturnType\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.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, abiParameter)\n })\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (\n matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs\n ) {\n const ambiguousTypes = getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AbiItemAmbiguityError(\n {\n abiItem,\n type: ambiguousTypes[0],\n },\n {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1],\n },\n )\n }\n\n matchedAbiItem = abiItem\n }\n }\n\n if (matchedAbiItem)\n return matchedAbiItem as GetAbiItemReturnType\n return abiItems[0] as GetAbiItemReturnType\n}\n\ntype IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\n/** @internal */\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, { strict: false })\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\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameter[],\n targetParameters: readonly AbiParameter[],\n args: AbiItemArgs,\n): AbiParameter['type'][] | undefined {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex]\n const targetParameter = targetParameters[parameterIndex]\n\n if (\n sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter\n )\n return getAmbiguousTypes(\n sourceParameter.components,\n targetParameter.components,\n (args as any)[parameterIndex],\n )\n\n const types = [sourceParameter.type, targetParameter.type]\n\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20')) return true\n if (types.includes('address') && types.includes('string'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\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 { 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\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","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\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\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 { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { BaseError } from './base.js'\n\nexport type AccountStateConflictErrorType = AccountStateConflictError & {\n name: 'AccountStateConflictError'\n}\n\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n })\n }\n}\n\nexport type StateAssignmentConflictErrorType = StateAssignmentConflictError & {\n name: 'StateAssignmentConflictError'\n}\n\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n })\n }\n}\n\n/** @internal */\nexport function prettyStateMapping(stateMapping: StateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`\n }, '')\n}\n\nexport function prettyStateOverride(stateOverride: StateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`\n if (state.nonce) val += ` nonce: ${state.nonce}\\n`\n if (state.balance) val += ` balance: ${state.balance}\\n`\n if (state.code) val += ` code: ${state.code}\\n`\n if (state.state) {\n val += ' state:\\n'\n val += prettyStateMapping(state.state)\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n'\n val += prettyStateMapping(state.stateDiff)\n }\n return val\n }, ' State Override:\\n')\n .slice(0, -1)\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 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 { name: 'FeeConflictError' },\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n })\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\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 '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n })\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\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 name: 'InvalidSerializedTransactionError',\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 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 { name: 'InvalidStorageKeySizeError' },\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'TransactionExecutionError',\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n blockTag?: BlockTag | undefined\n hash?: Hash | undefined\n index?: number | undefined\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 name: 'TransactionNotFoundError',\n })\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\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 name: 'TransactionReceiptNotFoundError',\n },\n )\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n { name: 'WaitForTransactionReceiptTimeoutError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nexport type ErrorType = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\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 { prettyStateOverride } from './stateOverride.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 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 stateOverride,\n }: CallParameters & {\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n let 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 if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`\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 name: 'CallExecutionError',\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[] | undefined\n override cause: BaseError\n contractAddress?: Address | undefined\n formattedArgs?: string | undefined\n functionName: string\n sender?: Address | undefined\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 | undefined\n contractAddress?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\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 prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'ContractFunctionExecutionError',\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 data?: DecodeErrorResultReturnType | undefined\n reason?: string | undefined\n signature?: Hex | undefined\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: {\n abi: Abi\n data?: Hex | undefined\n functionName: string\n message?: string | undefined\n }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined = undefined\n let metaMessages: string[] | undefined\n let reason: string | undefined\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 name: 'ContractFunctionRevertedError',\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 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 name: 'ContractFunctionZeroDataError',\n })\n }\n}\n\nexport type CounterfactualDeploymentFailedErrorType =\n CounterfactualDeploymentFailedError & {\n name: 'CounterfactualDeploymentFailedError'\n }\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }: { factory?: Address | undefined }) {\n super(\n `Deployment for counterfactual contract call failed${\n factory ? ` for factory \"${factory}\".` : ''\n }`,\n {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n },\n )\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n\n data?: Hex | { data?: Hex | undefined } | undefined\n\n constructor({\n data,\n message,\n }: {\n data?: Hex | { data?: Hex | undefined } | undefined\n message?: string | undefined\n }) {\n super(message || '', { name: 'RawContractError' })\n this.data = data\n }\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n data: Hex\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | undefined }\n : { functionName: functionName | allFunctionNames }\n : { functionName?: functionName | allFunctionNames | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type DecodeFunctionResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n> = ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n args\n>\n\nexport type DecodeFunctionResultErrorType =\n | AbiFunctionNotFoundErrorType\n | AbiFunctionOutputsNotFoundErrorType\n | DecodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function decodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n const args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n>(\n parameters: DecodeFunctionResultParameters,\n): DecodeFunctionResultReturnType {\n const { abi, args, functionName, data } =\n parameters as DecodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, args, name: functionName })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\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)\n return values as DecodeFunctionResultReturnType\n if (values && values.length === 1)\n return values[0] as DecodeFunctionResultReturnType\n return undefined as DecodeFunctionResultReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n hasConstructor = abi extends Abi\n ? Abi extends abi\n ? true\n : [Extract] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractConstructorArgs,\n> = {\n abi: abi\n bytecode: Hex\n} & UnionEvaluate<\n hasConstructor extends false\n ? { args?: undefined }\n : readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n>\n\nexport type EncodeDeployDataReturnType = Hex\n\nexport type EncodeDeployDataErrorType =\n | AbiConstructorNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | ErrorType\n\nexport function encodeDeployData(\n parameters: EncodeDeployDataParameters,\n): EncodeDeployDataReturnType {\n const { abi, args, bytecode } = parameters as EncodeDeployDataParameters\n if (!args || args.length === 0) return bytecode\n\n const description = abi.find((x) => 'type' in x && x.type === 'constructor')\n if (!description) throw new AbiConstructorNotFoundError({ docsPath })\n if (!('inputs' in description))\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n if (!description.inputs || description.inputs.length === 0)\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n\n const data = encodeAbiParameters(description.inputs, args)\n return concatHex([bytecode, data!])\n}\n","import type {\n Abi,\n AbiStateMutability,\n ExtractAbiFunction,\n ExtractAbiFunctions,\n} from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionData'\n\nexport type PrepareEncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<{ args?: allArgs | undefined }> &\n (hasFunctions extends true ? unknown : never)\n\nexport type PrepareEncodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n> = {\n abi: abi extends Abi\n ? functionName extends ContractFunctionName\n ? [ExtractAbiFunction]\n : abi\n : Abi\n functionName: Hex\n}\n\nexport type PrepareEncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function prepareEncodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: PrepareEncodeFunctionDataParameters,\n): PrepareEncodeFunctionDataReturnType {\n const { abi, args, functionName } =\n parameters as PrepareEncodeFunctionDataParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n } as unknown as PrepareEncodeFunctionDataReturnType\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport type { AbiFunctionNotFoundErrorType } from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport type { FormatAbiItemErrorType } from './formatAbiItem.js'\nimport type { GetAbiItemErrorType } from './getAbiItem.js'\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js'\n\nexport type EncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | Hex\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionDataReturnType = Hex\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionDataParameters,\n): EncodeFunctionDataReturnType {\n const { args } = parameters as EncodeFunctionDataParameters\n\n const { abi, functionName } = (() => {\n if (\n parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x')\n )\n return parameters as { abi: Abi; functionName: Hex }\n return prepareEncodeFunctionData(parameters)\n })()\n\n const abiItem = abi[0]\n const signature = functionName\n\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\n : undefined\n return concatHex([signature, data ?? '0x'])\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 | undefined\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 { 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 constructor({\n cause,\n message,\n }: { cause?: BaseError | undefined; message?: string | undefined } = {}) {\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 name: 'ExecutionRevertedError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooHighError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooLowError',\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause, name: 'NonceTooHighError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\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, name: 'NonceTooLowError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause, name: 'NonceMaxValueError' },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage =\n /insufficient funds|exceeds transaction sender account balance/\n constructor({ cause }: { cause?: BaseError | undefined } = {}) {\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 name: 'InsufficientFundsError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\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 name: 'IntrinsicGasTooHighError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n name: 'IntrinsicGasTooLowError',\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 constructor({ cause }: { cause?: BaseError | undefined }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\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 constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\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 name: 'TipAboveFeeCapError',\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }: { cause?: BaseError | undefined }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\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 body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\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 constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; data?: unknown; 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 name: 'RpcRequestError',\n })\n this.code = error.code\n this.data = error.data\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\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 name: 'TimeoutError',\n })\n }\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'\nimport type { ExactPartial } from '../../types/utils.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 = ExactPartial<\n SendTransactionParameters\n>\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 =\n err instanceof BaseError\n ? err.walk(\n (e) =>\n (e as { code: number } | null | undefined)?.code ===\n ExecutionRevertedError.code,\n )\n : err\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\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 { 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 | undefined\n docsPath?: string | undefined\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","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'] | undefined },\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 { AuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { bytesToHex, numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n chain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n request: ExactPartial,\n) {\n const rpcRequest = {} as RpcTransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(\n request.authorizationList,\n )\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = (request.blobs as ByteArray[]).map((x) =>\n bytesToHex(x),\n )\n else rpcRequest.blobs = request.blobs\n }\n if (typeof request.data !== 'undefined') rpcRequest.data = request.data\n if (typeof request.from !== 'undefined') rpcRequest.from = request.from\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce)\n if (typeof request.to !== 'undefined') rpcRequest.to = request.to\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type]\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value)\n\n return rpcRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: AuthorizationList,\n): RpcAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n address: authorization.contractAddress,\n r: authorization.r,\n s: authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }) as any,\n ) as RpcAuthorizationList\n}\n","/** @internal */\nexport type PromiseWithResolvers = {\n promise: Promise\n resolve: (value: type | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\n/** @internal */\nexport function withResolvers(): PromiseWithResolvers {\n let resolve: PromiseWithResolvers['resolve'] = () => undefined\n let reject: PromiseWithResolvers['reject'] = () => undefined\n\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_\n reject = reject_\n })\n\n return { promise, resolve, reject }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type PromiseWithResolvers, withResolvers } from './withResolvers.js'\n\ntype Resolved = [\n result: returnType[number],\n results: returnType,\n]\n\ntype SchedulerItem = {\n args: unknown\n resolve: PromiseWithResolvers['resolve']\n reject: PromiseWithResolvers['reject']\n}\n\ntype BatchResultsCompareFn = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise>\n : (args: parameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\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 parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i]\n resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i]\n reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\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: parameters) {\n const { promise, resolve, reject } = withResolvers()\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, resolve, reject })\n return promise\n }\n\n setScheduler({ args, resolve, reject })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n InvalidBytesLengthError,\n type InvalidBytesLengthErrorType,\n} from '../errors/data.js'\nimport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from '../errors/stateOverride.js'\nimport type {\n RpcAccountStateOverride,\n RpcStateMapping,\n RpcStateOverride,\n} from '../types/rpc.js'\nimport type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { isAddress } from './address/isAddress.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\n\ntype SerializeStateMappingParameters = StateMapping | undefined\n\ntype SerializeStateMappingErrorType = InvalidBytesLengthErrorType\n\n/** @internal */\nexport function serializeStateMapping(\n stateMapping: SerializeStateMappingParameters,\n): RpcStateMapping | undefined {\n if (!stateMapping || stateMapping.length === 0) return undefined\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n })\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n })\n acc[slot] = value\n return acc\n }, {} as RpcStateMapping)\n}\n\ntype SerializeAccountStateOverrideParameters = Omit<\n StateOverride[number],\n 'address'\n>\n\ntype SerializeAccountStateOverrideErrorType =\n | NumberToHexErrorType\n | StateAssignmentConflictErrorType\n | SerializeStateMappingErrorType\n\n/** @internal */\nexport function serializeAccountStateOverride(\n parameters: SerializeAccountStateOverrideParameters,\n): RpcAccountStateOverride {\n const { balance, nonce, state, stateDiff, code } = parameters\n const rpcAccountStateOverride: RpcAccountStateOverride = {}\n if (code !== undefined) rpcAccountStateOverride.code = code\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance)\n if (nonce !== undefined) rpcAccountStateOverride.nonce = numberToHex(nonce)\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state)\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state) throw new StateAssignmentConflictError()\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff)\n }\n return rpcAccountStateOverride\n}\n\ntype SerializeStateOverrideParameters = StateOverride | undefined\n\nexport type SerializeStateOverrideErrorType =\n | InvalidAddressErrorType\n | AccountStateConflictErrorType\n | SerializeAccountStateOverrideErrorType\n\n/** @internal */\nexport function serializeStateOverride(\n parameters?: SerializeStateOverrideParameters,\n): RpcStateOverride | undefined {\n if (!parameters) return undefined\n const rpcStateOverride: RpcStateOverride = {}\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address })\n rpcStateOverride[address] = serializeAccountStateOverride(accountState)\n }\n return rpcStateOverride\n}\n","export const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { maxUint256 } from '../../constants/number.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 type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = ExactPartial<\n SendTransactionParameters\n>\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 > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import { type Address, parseAbi } 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 {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n} from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ChainDoesNotSupportContract,\n ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n CounterfactualDeploymentFailedError,\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 { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.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 {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type CallParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Whether or not to enable multicall batching on this call. */\n batch?: boolean | undefined\n /** Bytecode to perform the call on. */\n code?: Hex | undefined\n /** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). */\n factory?: Address | undefined\n /** Calldata to execute on the factory to deploy the contract. */\n factoryData?: Hex | undefined\n /** State overrides for the call. */\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedCall =\n FormattedTransactionRequest\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | ScheduleMulticallErrorType\n | RequestErrorType\n | ToDeploylessCallViaBytecodeDataErrorType\n | ToDeploylessCallViaFactoryDataErrorType\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\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 blobs,\n code,\n data: data_,\n factory,\n factoryData,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n stateOverride,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n if (code && (factory || factoryData))\n throw new BaseError(\n 'Cannot provide both `code` & `factory`/`factoryData` as parameters.',\n )\n if (code && to)\n throw new BaseError('Cannot provide both `code` & `to` as parameters.')\n\n // Check if the call is deployless via bytecode.\n const deploylessCallViaBytecode = code && data_\n // Check if the call is deployless via a factory.\n const deploylessCallViaFactory = factory && factoryData && to && data_\n const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory\n\n const data = (() => {\n if (deploylessCallViaBytecode)\n return toDeploylessCallViaBytecodeData({\n code,\n data: data_,\n })\n if (deploylessCallViaFactory)\n return toDeploylessCallViaFactoryData({\n data: data_,\n factory,\n factoryData,\n to,\n })\n return data_\n })()\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\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 blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to: deploylessCall ? undefined : to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) {\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: rpcStateOverride\n ? [\n request as ExactPartial,\n block,\n rpcStateOverride,\n ]\n : [request as ExactPartial, block],\n })\n if (response === '0x') return { data: undefined }\n return { data: response }\n } catch (err) {\n const data = getRevertErrorData(err)\n\n // Check for CCIP-Read offchain lookup signature.\n const { offchainLookup, offchainLookupSignature } = await import(\n '../../utils/ccip.js'\n )\n if (\n client.ccipRead !== false &&\n data?.slice(0, 10) === offchainLookupSignature &&\n to\n )\n return { data: await offchainLookup(client, { data, to }) }\n\n // Check for counterfactual deployment error.\n if (deploylessCall && data?.slice(0, 10) === '0x101bb98d')\n throw new CounterfactualDeploymentFailedError({ factory })\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 | undefined\n to: Address\n}\n\ntype 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\ntype ToDeploylessCallViaBytecodeDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaBytecodeData(parameters: {\n code: Hex\n data: Hex\n}) {\n const { code, data } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(bytes, bytes)']),\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [code, data],\n })\n}\n\ntype ToDeploylessCallViaFactoryDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaFactoryData(parameters: {\n data: Hex\n factory: Address\n factoryData: Hex\n to: Address\n}) {\n const { data, factory, factoryData, to } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(address, bytes, address, bytes)']),\n bytecode: deploylessCallViaFactoryBytecode,\n args: [to, data, factory, factoryData],\n })\n}\n\n/** @internal */\nexport type GetRevertErrorDataErrorType = ErrorType\n\n/** @internal */\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 { Address } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type OffchainLookupErrorType = OffchainLookupError & {\n name: 'OffchainLookupError'\n}\nexport class OffchainLookupError extends BaseError {\n constructor({\n callbackSelector,\n cause,\n data,\n extraData,\n sender,\n urls,\n }: {\n callbackSelector: Hex\n cause: BaseError\n data: Hex\n extraData: Hex\n sender: Address\n urls: readonly string[]\n }) {\n super(\n cause.shortMessage ||\n 'An error occurred while fetching for an offchain result.',\n {\n cause,\n metaMessages: [\n ...(cause.metaMessages || []),\n cause.metaMessages?.length ? '' : [],\n 'Offchain Gateway Call:',\n urls && [\n ' Gateway URL(s):',\n ...urls.map((url) => ` ${getUrl(url)}`),\n ],\n ` Sender: ${sender}`,\n ` Data: ${data}`,\n ` Callback selector: ${callbackSelector}`,\n ` Extra data: ${extraData}`,\n ].flat(),\n name: 'OffchainLookupError',\n },\n )\n }\n}\n\nexport type OffchainLookupResponseMalformedErrorType =\n OffchainLookupResponseMalformedError & {\n name: 'OffchainLookupResponseMalformedError'\n }\nexport class OffchainLookupResponseMalformedError extends BaseError {\n constructor({ result, url }: { result: any; url: string }) {\n super(\n 'Offchain gateway response is malformed. Response data must be a hex value.',\n {\n metaMessages: [\n `Gateway URL: ${getUrl(url)}`,\n `Response: ${stringify(result)}`,\n ],\n name: 'OffchainLookupResponseMalformedError',\n },\n )\n }\n}\n\n/** @internal */\nexport type OffchainLookupSenderMismatchErrorType =\n OffchainLookupSenderMismatchError & {\n name: 'OffchainLookupSenderMismatchError'\n }\nexport class OffchainLookupSenderMismatchError extends BaseError {\n constructor({ sender, to }: { sender: Address; to: Address }) {\n super(\n 'Reverted sender address does not match target contract address (`to`).',\n {\n metaMessages: [\n `Contract address: ${to}`,\n `OffchainLookup sender address: ${sender}`,\n ],\n name: 'OffchainLookupSenderMismatchError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { isAddress } from './isAddress.js'\n\nexport type IsAddressEqualReturnType = boolean\nexport type IsAddressEqualErrorType = InvalidAddressErrorType | ErrorType\n\nexport function isAddressEqual(a: Address, b: Address) {\n if (!isAddress(a, { strict: false }))\n throw new InvalidAddressError({ address: a })\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b })\n return a.toLowerCase() === b.toLowerCase()\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { BaseError } from '../errors/base.js'\nimport {\n OffchainLookupError,\n type OffchainLookupErrorType as OffchainLookupErrorType_,\n OffchainLookupResponseMalformedError,\n type OffchainLookupResponseMalformedErrorType,\n OffchainLookupSenderMismatchError,\n} from '../errors/ccip.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n} from '../errors/request.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\n\nimport type { Client } from '../clients/createClient.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport { decodeErrorResult } from './abi/decodeErrorResult.js'\nimport { encodeAbiParameters } from './abi/encodeAbiParameters.js'\nimport { isAddressEqual } from './address/isAddressEqual.js'\nimport { concat } from './data/concat.js'\nimport { isHex } from './data/isHex.js'\nimport { stringify } from './stringify.js'\n\nexport const offchainLookupSignature = '0x556f1830'\nexport const offchainLookupAbiItem = {\n name: 'OffchainLookup',\n type: 'error',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'urls',\n type: 'string[]',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n {\n name: 'callbackFunction',\n type: 'bytes4',\n },\n {\n name: 'extraData',\n type: 'bytes',\n },\n ],\n} as const satisfies Abi[number]\n\nexport type OffchainLookupErrorType = OffchainLookupErrorType_ | ErrorType\n\nexport async function offchainLookup(\n client: Client,\n {\n blockNumber,\n blockTag,\n data,\n to,\n }: Pick & {\n data: Hex\n to: Address\n },\n): Promise {\n const { args } = decodeErrorResult({\n data,\n abi: [offchainLookupAbiItem],\n })\n const [sender, urls, callData, callbackSelector, extraData] = args\n\n const { ccipRead } = client\n const ccipRequest_ =\n ccipRead && typeof ccipRead?.request === 'function'\n ? ccipRead.request\n : ccipRequest\n\n try {\n if (!isAddressEqual(to, sender))\n throw new OffchainLookupSenderMismatchError({ sender, to })\n\n const result = await ccipRequest_({ data: callData, sender, urls })\n\n const { data: data_ } = await call(client, {\n blockNumber,\n blockTag,\n data: concat([\n callbackSelector,\n encodeAbiParameters(\n [{ type: 'bytes' }, { type: 'bytes' }],\n [result, extraData],\n ),\n ]),\n to,\n } as CallParameters)\n\n return data_!\n } catch (err) {\n throw new OffchainLookupError({\n callbackSelector,\n cause: err as BaseError,\n data,\n extraData,\n sender,\n urls,\n })\n }\n}\n\nexport type CcipRequestParameters = {\n data: Hex\n sender: Address\n urls: readonly string[]\n}\n\nexport type CcipRequestReturnType = Hex\n\nexport type CcipRequestErrorType =\n | HttpRequestErrorType\n | OffchainLookupResponseMalformedErrorType\n | ErrorType\n\nexport async function ccipRequest({\n data,\n sender,\n urls,\n}: CcipRequestParameters): Promise {\n let error = new Error('An unknown error occurred.')\n\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i]\n const method = url.includes('{data}') ? 'GET' : 'POST'\n const body = method === 'POST' ? { data, sender } : undefined\n const headers: HeadersInit =\n method === 'POST' ? { 'Content-Type': 'application/json' } : {}\n\n try {\n const response = await fetch(\n url.replace('{sender}', sender).replace('{data}', data),\n {\n body: JSON.stringify(body),\n headers,\n method,\n },\n )\n\n let result: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n ) {\n result = (await response.json()).data\n } else {\n result = (await response.text()) as any\n }\n\n if (!response.ok) {\n error = new HttpRequestError({\n body,\n details: result?.error\n ? stringify(result.error)\n : response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n continue\n }\n\n if (!isHex(result)) {\n error = new OffchainLookupResponseMalformedError({\n result,\n url,\n })\n continue\n }\n\n return result\n } catch (err) {\n error = new HttpRequestError({\n body,\n details: (err as Error).message,\n url,\n })\n }\n }\n\n throw error\n}\n"],"mappings":";AAAO,IAAM,UAAU;;;ACUjB,IAAO,YAAP,MAAO,mBAAkB,MAAK;EAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,UAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,UAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,UAAM,UAAU;MACd,gBAAgB;MAChB;MACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;MACrD,GAAIA,YAAW,CAAC,4BAA4BA,SAAQ,EAAE,IAAI,CAAA;MAC1D,GAAI,UAAU,CAAC,YAAY,OAAO,EAAE,IA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S,KAAI;MAC/B;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,gBAAQ,IAAI,iBAAiB;UAC3B;UACA,SAAS,QAAQ,QACb,UAAU,OAAO,KAAK,IACtB,SAAS;UACb,SAAS,SAAS;UAClB,QAAQ,SAAS;UACjB;SACD;AACD;MACF;AAEA,UAAI,CAAC,MAAM,MAAM,GAAG;AAClB,gBAAQ,IAAI,qCAAqC;UAC/C;UACA;SACD;AACD;MACF;AAEA,aAAO;IACT,SAAS,KAAK;AACZ,cAAQ,IAAI,iBAAiB;QAC3B;QACA,SAAU,IAAc;QACxB;OACD;IACH;EACF;AAEA,QAAM;AACR;","names":["docsPath","version","docsPath","version","BaseError","docsPath","version","BaseError","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","BaseError","docsPath","BaseError","docsPath","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","size","BaseError","size","BaseError","size","size","size","encoder","BaseError","toBytes","toBytes","toBytes","toBytes","BaseError","BaseError","size","hash","BaseError","size","bytesRegex","integerRegex","size","integerRegex","length","BaseError","data","length","consumed","value","size","formatAbiItem","value","BaseError","BaseError","BaseError","BaseError","docsPath","BaseError","docsPath","docsPath","formatAbiItem","BaseError","BaseError","BaseError","docsPath","cause","formatted","args","split","BaseError","data","offchainLookup","offchainLookupSignature","args","size","BaseError"]} \ No newline at end of file diff --git a/dist/chunk-PR4QN5HX.js b/dist/chunk-PR4QN5HX.js new file mode 100644 index 0000000..e9ed04f --- /dev/null +++ b/dist/chunk-PR4QN5HX.js @@ -0,0 +1,43 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +export { + __require, + __commonJS, + __export, + __toESM +}; +//# sourceMappingURL=chunk-PR4QN5HX.js.map \ No newline at end of file diff --git a/dist/chunk-PR4QN5HX.js.map b/dist/chunk-PR4QN5HX.js.map new file mode 100644 index 0000000..84c51b2 --- /dev/null +++ b/dist/chunk-PR4QN5HX.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..0a5eb2b --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,41 @@ +import { Plugin } from '@elizaos/core'; +import { Keypair } from '@solana/web3.js'; +import { DeriveKeyResponse, TdxQuoteHashAlgorithms } from '@phala/dstack-sdk'; +import { PrivateKeyAccount } from 'viem'; + +declare enum TEEMode { + OFF = "OFF", + LOCAL = "LOCAL",// For local development with simulator + DOCKER = "DOCKER",// For docker development with simulator + PRODUCTION = "PRODUCTION" +} +interface RemoteAttestationQuote { + quote: string; + timestamp: number; +} + +declare class DeriveKeyProvider { + private client; + private raProvider; + constructor(teeMode?: string); + private generateDeriveKeyAttestation; + rawDeriveKey(path: string, subject: string): Promise; + deriveEd25519Keypair(path: string, subject: string, agentId: string): Promise<{ + keypair: Keypair; + attestation: RemoteAttestationQuote; + }>; + deriveEcdsaKeypair(path: string, subject: string, agentId: string): Promise<{ + keypair: PrivateKeyAccount; + attestation: RemoteAttestationQuote; + }>; +} + +declare class RemoteAttestationProvider { + private client; + constructor(teeMode?: string); + generateAttestation(reportData: string, hashAlgorithm?: TdxQuoteHashAlgorithms): Promise; +} + +declare const teePlugin: Plugin; + +export { DeriveKeyProvider, RemoteAttestationProvider, type RemoteAttestationQuote, TEEMode, teePlugin }; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..99b5fc2 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,1603 @@ +import { + secp256k1 +} from "./chunk-4L6P6TY5.js"; +import { + BaseError, + BytesSizeMismatchError, + FeeCapTooHighError, + Hash, + InvalidAddressError, + InvalidChainIdError, + InvalidLegacyVError, + InvalidSerializableTransactionError, + InvalidStorageKeySizeError, + TipAboveFeeCapError, + aexists, + aoutput, + bytesRegex, + bytesToHex, + checksumAddress, + concat, + concatHex, + createCursor, + createView, + encodeAbiParameters, + hexToBigInt, + hexToBytes, + hexToNumber, + integerRegex, + isAddress, + isHex, + keccak256, + maxUint256, + numberToHex, + rotr, + size, + slice, + stringToHex, + stringify, + toBytes, + toBytes2, + toHex, + trim, + wrapConstructor +} from "./chunk-KSHJJL6X.js"; +import "./chunk-PR4QN5HX.js"; + +// src/providers/remoteAttestationProvider.ts +import { + elizaLogger +} from "@elizaos/core"; +import { TappdClient } from "@phala/dstack-sdk"; + +// src/types/tee.ts +var TEEMode = /* @__PURE__ */ ((TEEMode2) => { + TEEMode2["OFF"] = "OFF"; + TEEMode2["LOCAL"] = "LOCAL"; + TEEMode2["DOCKER"] = "DOCKER"; + TEEMode2["PRODUCTION"] = "PRODUCTION"; + return TEEMode2; +})(TEEMode || {}); + +// src/providers/remoteAttestationProvider.ts +var RemoteAttestationProvider = class { + client; + constructor(teeMode) { + let endpoint; + switch (teeMode) { + case "LOCAL" /* LOCAL */: + endpoint = "http://localhost:8090"; + elizaLogger.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case "DOCKER" /* DOCKER */: + endpoint = "http://host.docker.internal:8090"; + elizaLogger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case "PRODUCTION" /* PRODUCTION */: + endpoint = void 0; + elizaLogger.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + } + async generateAttestation(reportData, hashAlgorithm) { + try { + elizaLogger.log("Generating attestation for: ", reportData); + const tdxQuote = await this.client.tdxQuote(reportData, hashAlgorithm); + const rtmrs = tdxQuote.replayRtmrs(); + elizaLogger.log( + `rtmr0: ${rtmrs[0]} +rtmr1: ${rtmrs[1]} +rtmr2: ${rtmrs[2]} +rtmr3: ${rtmrs[3]}f` + ); + const quote = { + quote: tdxQuote.quote, + timestamp: Date.now() + }; + elizaLogger.log("Remote attestation quote: ", quote); + return quote; + } catch (error) { + console.error("Error generating remote attestation:", error); + throw new Error( + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` + ); + } + } +}; +var remoteAttestationProvider = { + get: async (runtime, _message, _state) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new RemoteAttestationProvider(teeMode); + const agentId = runtime.agentId; + try { + elizaLogger.log("Generating attestation for: ", agentId); + const attestation = await provider.generateAttestation(agentId, "raw"); + return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; + } catch (error) { + console.error("Error in remote attestation provider:", error); + throw new Error( + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` + ); + } + } +}; + +// src/providers/deriveKeyProvider.ts +import { + elizaLogger as elizaLogger2 +} from "@elizaos/core"; +import { Keypair } from "@solana/web3.js"; +import crypto from "crypto"; +import { TappdClient as TappdClient2 } from "@phala/dstack-sdk"; + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/_md.js +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +var Chi = (a, b, c) => a & b ^ ~a & c; +var Maj = (a, b, c) => a & b ^ a & c ^ b & c; +var HashMD = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +}; + +// ../../node_modules/viem/node_modules/@noble/hashes/esm/sha256.js +var SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA256 = class extends HashMD { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + +// ../../node_modules/viem/_esm/accounts/toAccount.js +function toAccount(source) { + if (typeof source === "string") { + if (!isAddress(source, { strict: false })) + throw new InvalidAddressError({ address: source }); + return { + address: source, + type: "json-rpc" + }; + } + if (!isAddress(source.address, { strict: false })) + throw new InvalidAddressError({ address: source.address }); + return { + address: source.address, + nonceManager: source.nonceManager, + sign: source.sign, + experimental_signAuthorization: source.experimental_signAuthorization, + signMessage: source.signMessage, + signTransaction: source.signTransaction, + signTypedData: source.signTypedData, + source: "custom", + type: "local" + }; +} + +// ../../node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js +function publicKeyToAddress(publicKey) { + const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); + return checksumAddress(`0x${address}`); +} + +// ../../node_modules/viem/_esm/utils/signature/serializeSignature.js +function serializeSignature({ r, s, to = "hex", 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"); + })(); + const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; + if (to === "hex") + return signature; + return hexToBytes(signature); +} + +// ../../node_modules/viem/_esm/accounts/utils/sign.js +var extraEntropy = false; +async function sign({ hash, privateKey, to = "object" }) { + const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), { lowS: true, extraEntropy }); + const signature = { + r: numberToHex(r, { size: 32 }), + s: numberToHex(s, { size: 32 }), + v: recovery ? 28n : 27n, + yParity: recovery + }; + return (() => { + if (to === "bytes" || to === "hex") + return serializeSignature({ ...signature, to }); + return signature; + })(); +} + +// ../../node_modules/viem/_esm/utils/encoding/toRlp.js +function toRlp(bytes, to = "hex") { + const encodable = getEncodable(bytes); + const cursor = createCursor(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (to === "hex") + return bytesToHex(cursor.bytes); + return cursor.bytes; +} +function getEncodable(bytes) { + if (Array.isArray(bytes)) + return getEncodableList(bytes.map((x) => getEncodable(x))); + return getEncodableBytes(bytes); +} +function getEncodableList(list) { + const bodyLength = list.reduce((acc, x) => acc + x.length, 0); + const sizeOfBodyLength = getSizeOfLength(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; + })(); + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); + } + for (const { encode } of list) { + encode(cursor); + } + } + }; +} +function getEncodableBytes(bytesOrHex) { + const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength(bytes.length); + const length = (() => { + if (bytes.length === 1 && bytes[0] < 128) + return 1; + if (bytes.length <= 55) + return 1 + bytes.length; + return 1 + sizeOfBytesLength + bytes.length; + })(); + return { + length, + encode(cursor) { + if (bytes.length === 1 && bytes[0] < 128) { + cursor.pushBytes(bytes); + } else if (bytes.length <= 55) { + cursor.pushByte(128 + bytes.length); + cursor.pushBytes(bytes); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes.length); + else + cursor.pushUint32(bytes.length); + cursor.pushBytes(bytes); + } + } + }; +} +function getSizeOfLength(length) { + if (length < 2 ** 8) + return 1; + if (length < 2 ** 16) + return 2; + if (length < 2 ** 24) + return 3; + if (length < 2 ** 32) + return 4; + throw new BaseError("Length is too large."); +} + +// ../../node_modules/viem/_esm/experimental/eip7702/utils/hashAuthorization.js +function hashAuthorization(parameters) { + const { chainId, contractAddress, nonce, to } = parameters; + const hash = keccak256(concatHex([ + "0x05", + toRlp([ + chainId ? numberToHex(chainId) : "0x", + contractAddress, + nonce ? numberToHex(nonce) : "0x" + ]) + ])); + if (to === "bytes") + return hexToBytes(hash); + return hash; +} + +// ../../node_modules/viem/_esm/accounts/utils/signAuthorization.js +async function experimental_signAuthorization(parameters) { + const { contractAddress, chainId, nonce, privateKey, to = "object" } = parameters; + const signature = await sign({ + hash: hashAuthorization({ contractAddress, chainId, nonce }), + privateKey, + to + }); + if (to === "object") + return { + contractAddress, + chainId, + nonce, + ...signature + }; + return signature; +} + +// ../../node_modules/viem/_esm/constants/strings.js +var presignMessagePrefix = "Ethereum Signed Message:\n"; + +// ../../node_modules/viem/_esm/utils/signature/toPrefixedMessage.js +function toPrefixedMessage(message_) { + const message = (() => { + if (typeof message_ === "string") + return stringToHex(message_); + if (typeof message_.raw === "string") + return message_.raw; + return bytesToHex(message_.raw); + })(); + const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); + return concat([prefix, message]); +} + +// ../../node_modules/viem/_esm/utils/signature/hashMessage.js +function hashMessage(message, to_) { + return keccak256(toPrefixedMessage(message), to_); +} + +// ../../node_modules/viem/_esm/accounts/utils/signMessage.js +async function signMessage({ message, privateKey }) { + return await sign({ hash: hashMessage(message), privateKey, to: "hex" }); +} + +// ../../node_modules/viem/_esm/utils/blob/blobsToCommitments.js +function blobsToCommitments(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; + const commitments = []; + for (const blob of blobs) + commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); + return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x)); +} + +// ../../node_modules/viem/_esm/utils/blob/blobsToProofs.js +function blobsToProofs(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; + const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments; + const proofs = []; + for (let i = 0; i < blobs.length; i++) { + const blob = blobs[i]; + const commitment = commitments[i]; + proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + } + return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x)); +} + +// ../../node_modules/viem/_esm/utils/hash/sha256.js +function sha2562(value, to_) { + const to = to_ || "hex"; + const bytes = sha256(isHex(value, { strict: false }) ? toBytes2(value) : value); + if (to === "bytes") + return bytes; + return toHex(bytes); +} + +// ../../node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js +function commitmentToVersionedHash(parameters) { + const { commitment, version = 1 } = parameters; + const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); + const versionedHash = sha2562(commitment, "bytes"); + versionedHash.set([version], 0); + return to === "bytes" ? versionedHash : bytesToHex(versionedHash); +} + +// ../../node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js +function commitmentsToVersionedHashes(parameters) { + const { commitments, version } = parameters; + const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); + const hashes = []; + for (const commitment of commitments) { + hashes.push(commitmentToVersionedHash({ + commitment, + to, + version + })); + } + return hashes; +} + +// ../../node_modules/viem/_esm/constants/blob.js +var blobsPerTransaction = 6; +var bytesPerFieldElement = 32; +var fieldElementsPerBlob = 4096; +var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; +var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). +1 - // zero byte (0x00) appended to each field element. +1 * fieldElementsPerBlob * blobsPerTransaction; + +// ../../node_modules/viem/_esm/constants/kzg.js +var versionedHashVersionKzg = 1; + +// ../../node_modules/viem/_esm/errors/blob.js +var BlobSizeTooLargeError = class extends BaseError { + constructor({ maxSize, size: size2 }) { + super("Blob size is too large.", { + metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`], + name: "BlobSizeTooLargeError" + }); + } +}; +var EmptyBlobError = class extends BaseError { + constructor() { + super("Blob data must not be empty.", { name: "EmptyBlobError" }); + } +}; +var InvalidVersionedHashSizeError = class extends BaseError { + constructor({ hash, size: size2 }) { + super(`Versioned hash "${hash}" size is invalid.`, { + metaMessages: ["Expected: 32", `Received: ${size2}`], + name: "InvalidVersionedHashSizeError" + }); + } +}; +var InvalidVersionedHashVersionError = class extends BaseError { + constructor({ hash, version }) { + super(`Versioned hash "${hash}" version is invalid.`, { + metaMessages: [ + `Expected: ${versionedHashVersionKzg}`, + `Received: ${version}` + ], + name: "InvalidVersionedHashVersionError" + }); + } +}; + +// ../../node_modules/viem/_esm/utils/blob/toBlobs.js +function toBlobs(parameters) { + const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); + const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; + const size_ = size(data); + if (!size_) + throw new EmptyBlobError(); + if (size_ > maxBytesPerTransaction) + throw new BlobSizeTooLargeError({ + maxSize: maxBytesPerTransaction, + size: size_ + }); + const blobs = []; + let active = true; + let position = 0; + while (active) { + const blob = createCursor(new Uint8Array(bytesPerBlob)); + let size2 = 0; + while (size2 < fieldElementsPerBlob) { + const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); + blob.pushByte(0); + blob.pushBytes(bytes); + if (bytes.length < 31) { + blob.pushByte(128); + active = false; + break; + } + size2++; + position += 31; + } + blobs.push(blob); + } + return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes)); +} + +// ../../node_modules/viem/_esm/utils/blob/toBlobSidecars.js +function toBlobSidecars(parameters) { + const { data, kzg, to } = parameters; + const blobs = parameters.blobs ?? toBlobs({ data, to }); + const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); + const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); + const sidecars = []; + for (let i = 0; i < blobs.length; i++) + sidecars.push({ + blob: blobs[i], + commitment: commitments[i], + proof: proofs[i] + }); + return sidecars; +} + +// ../../node_modules/viem/_esm/experimental/eip7702/utils/serializeAuthorizationList.js +function serializeAuthorizationList(authorizationList) { + if (!authorizationList || authorizationList.length === 0) + return []; + const serializedAuthorizationList = []; + for (const authorization of authorizationList) { + const { contractAddress, chainId, nonce, ...signature } = authorization; + serializedAuthorizationList.push([ + chainId ? toHex(chainId) : "0x", + contractAddress, + nonce ? toHex(nonce) : "0x", + ...toYParitySignatureArray({}, signature) + ]); + } + return serializedAuthorizationList; +} + +// ../../node_modules/viem/_esm/utils/transaction/assertTransaction.js +function assertTransactionEIP7702(transaction) { + const { authorizationList } = transaction; + if (authorizationList) { + for (const authorization of authorizationList) { + const { contractAddress, chainId } = authorization; + if (!isAddress(contractAddress)) + throw new InvalidAddressError({ address: contractAddress }); + if (chainId < 0) + throw new InvalidChainIdError({ chainId }); + } + } + assertTransactionEIP1559(transaction); +} +function assertTransactionEIP4844(transaction) { + const { blobVersionedHashes } = transaction; + if (blobVersionedHashes) { + if (blobVersionedHashes.length === 0) + throw new EmptyBlobError(); + for (const hash of blobVersionedHashes) { + const size_ = size(hash); + const version = hexToNumber(slice(hash, 0, 1)); + if (size_ !== 32) + throw new InvalidVersionedHashSizeError({ hash, size: size_ }); + if (version !== versionedHashVersionKzg) + throw new InvalidVersionedHashVersionError({ + hash, + version + }); + } + } + assertTransactionEIP1559(transaction); +} +function assertTransactionEIP1559(transaction) { + const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +function assertTransactionEIP2930(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} +function assertTransactionLegacy(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (typeof chainId !== "undefined" && chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} + +// ../../node_modules/viem/_esm/utils/transaction/getTransactionType.js +function getTransactionType(transaction) { + if (transaction.type) + return transaction.type; + if (typeof transaction.authorizationList !== "undefined") + return "eip7702"; + if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") + return "eip4844"; + if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { + return "eip1559"; + } + if (typeof transaction.gasPrice !== "undefined") { + if (typeof transaction.accessList !== "undefined") + return "eip2930"; + return "legacy"; + } + throw new InvalidSerializableTransactionError({ transaction }); +} + +// ../../node_modules/viem/_esm/utils/transaction/serializeAccessList.js +function serializeAccessList(accessList) { + if (!accessList || accessList.length === 0) + return []; + const serializedAccessList = []; + for (let i = 0; i < accessList.length; i++) { + const { address, storageKeys } = accessList[i]; + for (let j = 0; j < storageKeys.length; j++) { + if (storageKeys[j].length - 2 !== 64) { + throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] }); + } + } + if (!isAddress(address, { strict: false })) { + throw new InvalidAddressError({ address }); + } + serializedAccessList.push([address, storageKeys]); + } + return serializedAccessList; +} + +// ../../node_modules/viem/_esm/utils/transaction/serializeTransaction.js +function serializeTransaction(transaction, signature) { + const type = getTransactionType(transaction); + if (type === "eip1559") + return serializeTransactionEIP1559(transaction, signature); + if (type === "eip2930") + return serializeTransactionEIP2930(transaction, signature); + if (type === "eip4844") + return serializeTransactionEIP4844(transaction, signature); + if (type === "eip7702") + return serializeTransactionEIP7702(transaction, signature); + return serializeTransactionLegacy(transaction, signature); +} +function serializeTransactionEIP7702(transaction, signature) { + const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP7702(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedAuthorizationList = serializeAuthorizationList(authorizationList); + return concatHex([ + "0x04", + toRlp([ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + serializedAuthorizationList, + ...toYParitySignatureArray(transaction, signature) + ]) + ]); +} +function serializeTransactionEIP4844(transaction, signature) { + const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP4844(transaction); + let blobVersionedHashes = transaction.blobVersionedHashes; + let sidecars = transaction.sidecars; + if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { + const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x)); + const kzg = transaction.kzg; + const commitments2 = blobsToCommitments({ + blobs: blobs2, + kzg + }); + if (typeof blobVersionedHashes === "undefined") + blobVersionedHashes = commitmentsToVersionedHashes({ + commitments: commitments2 + }); + if (typeof sidecars === "undefined") { + const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); + sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); + } + } + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x", + blobVersionedHashes ?? [], + ...toYParitySignatureArray(transaction, signature) + ]; + const blobs = []; + const commitments = []; + const proofs = []; + if (sidecars) + for (let i = 0; i < sidecars.length; i++) { + const { blob, commitment, proof } = sidecars[i]; + blobs.push(blob); + commitments.push(commitment); + proofs.push(proof); + } + return concatHex([ + "0x03", + sidecars ? ( + // If sidecars are enabled, envelope turns into a "wrapper": + toRlp([serializedTransaction, blobs, commitments, proofs]) + ) : ( + // If sidecars are disabled, standard envelope is used: + toRlp(serializedTransaction) + ) + ]); +} +function serializeTransactionEIP1559(transaction, signature) { + const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP1559(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x02", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionEIP2930(transaction, signature) { + const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction; + assertTransactionEIP2930(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x01", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionLegacy(transaction, signature) { + const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction; + assertTransactionLegacy(transaction); + let serializedTransaction = [ + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x" + ]; + if (signature) { + const v = (() => { + if (signature.v >= 35n) { + const inferredChainId = (signature.v - 35n) / 2n; + if (inferredChainId > 0) + return signature.v; + return 27n + (signature.v === 35n ? 0n : 1n); + } + if (chainId > 0) + return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); + const v2 = 27n + (signature.v === 27n ? 0n : 1n); + if (signature.v !== v2) + throw new InvalidLegacyVError({ v: signature.v }); + return v2; + })(); + const r = trim(signature.r); + const s = trim(signature.s); + serializedTransaction = [ + ...serializedTransaction, + toHex(v), + r === "0x00" ? "0x" : r, + s === "0x00" ? "0x" : s + ]; + } else if (chainId > 0) { + serializedTransaction = [ + ...serializedTransaction, + toHex(chainId), + "0x", + "0x" + ]; + } + return toRlp(serializedTransaction); +} +function toYParitySignatureArray(transaction, signature_) { + const signature = signature_ ?? transaction; + const { v, yParity } = signature; + if (typeof signature.r === "undefined") + return []; + if (typeof signature.s === "undefined") + return []; + if (typeof v === "undefined" && typeof yParity === "undefined") + return []; + const r = trim(signature.r); + const s = trim(signature.s); + const yParity_ = (() => { + if (typeof yParity === "number") + return yParity ? toHex(1) : "0x"; + if (v === 0n) + return "0x"; + if (v === 1n) + return toHex(1); + return v === 27n ? "0x" : toHex(1); + })(); + return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; +} + +// ../../node_modules/viem/_esm/accounts/utils/signTransaction.js +async function signTransaction(parameters) { + const { privateKey, transaction, serializer = serializeTransaction } = parameters; + const signableTransaction = (() => { + if (transaction.type === "eip4844") + return { + ...transaction, + sidecars: false + }; + return transaction; + })(); + const signature = await sign({ + hash: keccak256(serializer(signableTransaction)), + privateKey + }); + return serializer(transaction, signature); +} + +// ../../node_modules/viem/_esm/errors/typedData.js +var InvalidDomainError = class extends BaseError { + constructor({ domain }) { + super(`Invalid domain "${stringify(domain)}".`, { + metaMessages: ["Must be a valid EIP-712 domain."] + }); + } +}; +var InvalidPrimaryTypeError = class extends BaseError { + constructor({ primaryType, types }) { + super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { + docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", + metaMessages: ["Check that the primary type is a key in `types`."] + }); + } +}; +var InvalidStructTypeError = class extends BaseError { + constructor({ type }) { + super(`Struct type "${type}" is invalid.`, { + metaMessages: ["Struct type must not be a Solidity type."], + name: "InvalidStructTypeError" + }); + } +}; + +// ../../node_modules/viem/_esm/utils/typedData.js +function validateTypedData(parameters) { + const { domain, message, primaryType, types } = parameters; + const validateData = (struct, data) => { + for (const param of struct) { + const { name, type } = param; + const value = data[name]; + const integerMatch = type.match(integerRegex); + if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { + const [_type, base, size_] = integerMatch; + numberToHex(value, { + signed: base === "int", + size: Number.parseInt(size_) / 8 + }); + } + if (type === "address" && typeof value === "string" && !isAddress(value)) + throw new InvalidAddressError({ address: value }); + const bytesMatch = type.match(bytesRegex); + if (bytesMatch) { + const [_type, size_] = bytesMatch; + if (size_ && size(value) !== Number.parseInt(size_)) + throw new BytesSizeMismatchError({ + expectedSize: Number.parseInt(size_), + givenSize: size(value) + }); + } + const struct2 = types[type]; + if (struct2) { + validateReference(type); + validateData(struct2, value); + } + } + }; + if (types.EIP712Domain && domain) { + if (typeof domain !== "object") + throw new InvalidDomainError({ domain }); + validateData(types.EIP712Domain, domain); + } + if (primaryType !== "EIP712Domain") { + if (types[primaryType]) + validateData(types[primaryType], message); + else + throw new InvalidPrimaryTypeError({ primaryType, types }); + } +} +function getTypesForEIP712Domain({ domain }) { + return [ + typeof domain?.name === "string" && { name: "name", type: "string" }, + domain?.version && { name: "version", type: "string" }, + typeof domain?.chainId === "number" && { + name: "chainId", + type: "uint256" + }, + domain?.verifyingContract && { + name: "verifyingContract", + type: "address" + }, + domain?.salt && { name: "salt", type: "bytes32" } + ].filter(Boolean); +} +function validateReference(type) { + if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) + throw new InvalidStructTypeError({ type }); +} + +// ../../node_modules/viem/_esm/utils/signature/hashTypedData.js +function hashTypedData(parameters) { + const { domain = {}, message, primaryType } = parameters; + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData({ + domain, + message, + primaryType, + types + }); + const parts = ["0x1901"]; + if (domain) + parts.push(hashDomain({ + domain, + types + })); + if (primaryType !== "EIP712Domain") + parts.push(hashStruct({ + data: message, + primaryType, + types + })); + return keccak256(concat(parts)); +} +function hashDomain({ domain, types }) { + return hashStruct({ + data: domain, + primaryType: "EIP712Domain", + types + }); +} +function hashStruct({ data, primaryType, types }) { + const encoded = encodeData({ + data, + primaryType, + types + }); + return keccak256(encoded); +} +function encodeData({ data, primaryType, types }) { + const encodedTypes = [{ type: "bytes32" }]; + const encodedValues = [hashType({ primaryType, types })]; + for (const field of types[primaryType]) { + const [type, value] = encodeField({ + types, + name: field.name, + type: field.type, + value: data[field.name] + }); + encodedTypes.push(type); + encodedValues.push(value); + } + return encodeAbiParameters(encodedTypes, encodedValues); +} +function hashType({ primaryType, types }) { + const encodedHashType = toHex(encodeType({ primaryType, types })); + return keccak256(encodedHashType); +} +function encodeType({ primaryType, types }) { + let result = ""; + const unsortedDeps = findTypeDependencies({ primaryType, types }); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; + } + return result; +} +function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) { + const match = primaryType_.match(/^\w*/u); + const primaryType = match?.[0]; + if (results.has(primaryType) || types[primaryType] === void 0) { + return results; + } + results.add(primaryType); + for (const field of types[primaryType]) { + findTypeDependencies({ primaryType: field.type, types }, results); + } + return results; +} +function encodeField({ types, name, type, value }) { + if (types[type] !== void 0) { + return [ + { type: "bytes32" }, + keccak256(encodeData({ data: value, primaryType: type, types })) + ]; + } + if (type === "bytes") { + const prepend = value.length % 2 ? "0" : ""; + value = `0x${prepend + value.slice(2)}`; + return [{ type: "bytes32" }, keccak256(value)]; + } + if (type === "string") + return [{ type: "bytes32" }, keccak256(toHex(value))]; + if (type.lastIndexOf("]") === type.length - 1) { + const parsedType = type.slice(0, type.lastIndexOf("[")); + const typeValuePairs = value.map((item) => encodeField({ + name, + type: parsedType, + types, + value: item + })); + return [ + { type: "bytes32" }, + keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) + ]; + } + return [{ type }, value]; +} + +// ../../node_modules/viem/_esm/accounts/utils/signTypedData.js +async function signTypedData(parameters) { + const { privateKey, ...typedData } = parameters; + return await sign({ + hash: hashTypedData(typedData), + privateKey, + to: "hex" + }); +} + +// ../../node_modules/viem/_esm/accounts/privateKeyToAccount.js +function privateKeyToAccount(privateKey, options = {}) { + const { nonceManager } = options; + const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false)); + const address = publicKeyToAddress(publicKey); + const account = toAccount({ + address, + nonceManager, + async sign({ hash }) { + return sign({ hash, privateKey, to: "hex" }); + }, + async experimental_signAuthorization(authorization) { + return experimental_signAuthorization({ ...authorization, privateKey }); + }, + async signMessage({ message }) { + return signMessage({ message, privateKey }); + }, + async signTransaction(transaction, { serializer } = {}) { + return signTransaction({ privateKey, transaction, serializer }); + }, + async signTypedData(typedData) { + return signTypedData({ ...typedData, privateKey }); + } + }); + return { + ...account, + publicKey, + source: "privateKey" + }; +} + +// src/providers/deriveKeyProvider.ts +var DeriveKeyProvider = class { + client; + raProvider; + constructor(teeMode) { + let endpoint; + switch (teeMode) { + case "LOCAL" /* LOCAL */: + endpoint = "http://localhost:8090"; + elizaLogger2.log( + "TEE: Connecting to local simulator at localhost:8090" + ); + break; + case "DOCKER" /* DOCKER */: + endpoint = "http://host.docker.internal:8090"; + elizaLogger2.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); + break; + case "PRODUCTION" /* PRODUCTION */: + endpoint = void 0; + elizaLogger2.log( + "TEE: Running in production mode without simulator" + ); + break; + default: + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); + } + this.client = endpoint ? new TappdClient2(endpoint) : new TappdClient2(); + this.raProvider = new RemoteAttestationProvider(teeMode); + } + async generateDeriveKeyAttestation(agentId, publicKey) { + const deriveKeyData = { + agentId, + publicKey + }; + const reportdata = JSON.stringify(deriveKeyData); + elizaLogger2.log( + "Generating Remote Attestation Quote for Derive Key..." + ); + const quote = await this.raProvider.generateAttestation(reportdata); + elizaLogger2.log("Remote Attestation Quote generated successfully!"); + return quote; + } + async rawDeriveKey(path, subject) { + try { + if (!path || !subject) { + elizaLogger2.error( + "Path and Subject are required for key derivation" + ); + } + elizaLogger2.log("Deriving Raw Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + elizaLogger2.log("Raw Key Derived Successfully!"); + return derivedKey; + } catch (error) { + elizaLogger2.error("Error deriving raw key:", error); + throw error; + } + } + async deriveEd25519Keypair(path, subject, agentId) { + try { + if (!path || !subject) { + elizaLogger2.error( + "Path and Subject are required for key derivation" + ); + } + elizaLogger2.log("Deriving Key in TEE..."); + const derivedKey = await this.client.deriveKey(path, subject); + const uint8ArrayDerivedKey = derivedKey.asUint8Array(); + const hash = crypto.createHash("sha256"); + hash.update(uint8ArrayDerivedKey); + const seed = hash.digest(); + const seedArray = new Uint8Array(seed); + const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.publicKey.toBase58() + ); + elizaLogger2.log("Key Derived Successfully!"); + return { keypair, attestation }; + } catch (error) { + elizaLogger2.error("Error deriving key:", error); + throw error; + } + } + async deriveEcdsaKeypair(path, subject, agentId) { + try { + if (!path || !subject) { + elizaLogger2.error( + "Path and Subject are required for key derivation" + ); + } + elizaLogger2.log("Deriving ECDSA Key in TEE..."); + const deriveKeyResponse = await this.client.deriveKey(path, subject); + const hex = keccak256(deriveKeyResponse.asUint8Array()); + const keypair = privateKeyToAccount(hex); + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.address + ); + elizaLogger2.log("ECDSA Key Derived Successfully!"); + return { keypair, attestation }; + } catch (error) { + elizaLogger2.error("Error deriving ecdsa key:", error); + throw error; + } + } +}; +var deriveKeyProvider = { + get: async (runtime, _message, _state) => { + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new DeriveKeyProvider(teeMode); + const agentId = runtime.agentId; + try { + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + elizaLogger2.error( + "Wallet secret salt is not configured in settings" + ); + return ""; + } + try { + const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; + const solanaKeypair = await provider.deriveEd25519Keypair( + "/", + secretSalt, + agentId + ); + const evmKeypair = await provider.deriveEcdsaKeypair( + "/", + secretSalt, + agentId + ); + return JSON.stringify({ + solana: solanaKeypair.keypair.publicKey, + evm: evmKeypair.keypair.address + }); + } catch (error) { + elizaLogger2.error("Error creating PublicKey:", error); + return ""; + } + } catch (error) { + elizaLogger2.error("Error in derive key provider:", error.message); + return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`; + } + } +}; + +// src/actions/remoteAttestation.ts +import { fetch } from "undici"; +function hexToUint8Array(hex) { + hex = hex.trim(); + if (!hex) { + throw new Error("Invalid hex string"); + } + if (hex.startsWith("0x")) { + hex = hex.substring(2); + } + if (hex.length % 2 !== 0) { + throw new Error("Invalid hex string"); + } + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + const byte = parseInt(hex.slice(i, i + 2), 16); + if (isNaN(byte)) { + throw new Error("Invalid hex string"); + } + array[i / 2] = byte; + } + return array; +} +async function uploadUint8Array(data) { + const blob = new Blob([data], { type: "application/octet-stream" }); + const formData = new FormData(); + formData.append("file", blob, "quote.bin"); + return await fetch("https://proof.t16z.com/api/upload", { + method: "POST", + body: formData + }); +} +var remoteAttestationAction = { + name: "REMOTE_ATTESTATION", + similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"], + description: "Generate a remote attestation to prove that the agent is running in a TEE", + handler: async (runtime, _message, _state, _options, callback) => { + try { + const agentId = runtime.agentId; + const teeMode = runtime.getSetting("TEE_MODE"); + const provider = new RemoteAttestationProvider(teeMode); + const attestation = await provider.generateAttestation(agentId, "raw"); + const attestationData = hexToUint8Array(attestation.quote); + const response = await uploadUint8Array(attestationData); + const data = await response.json(); + callback({ + text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} + https://proof.t16z.com/reports/${data.checksum}`, + action: "NONE" + }); + return true; + } catch (error) { + console.error("Failed to fetch remote attestation: ", error); + return false; + } + }, + validate: async (_runtime) => { + return true; + }, + examples: [ + [ + { + user: "{{user1}}", + content: { + text: "If you are running in a TEE, generate a remote attestation" + } + }, + { + user: "{{user2}}", + content: { + text: "Of course, one second...", + action: "REMOTE_ATTESTATION" + } + } + ] + ] +}; + +// src/index.ts +var teePlugin = { + name: "tee", + description: "TEE plugin with actions to generate remote attestations and derive keys", + actions: [ + /* custom actions */ + remoteAttestationAction + ], + evaluators: [ + /* custom evaluators */ + ], + providers: [ + /* custom providers */ + remoteAttestationProvider, + deriveKeyProvider + ], + services: [ + /* custom services */ + ] +}; +export { + DeriveKeyProvider, + RemoteAttestationProvider, + TEEMode, + teePlugin +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..8164005 --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/providers/remoteAttestationProvider.ts","../src/types/tee.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/actions/remoteAttestation.ts","../src/index.ts"],"sourcesContent":["import {\n IAgentRuntime,\n Memory,\n Provider,\n State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { TdxQuoteResponse, TappdClient, TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\nimport { RemoteAttestationQuote, TEEMode } from \"../types/tee\";\n\nclass RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n elizaLogger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse =\n await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n elizaLogger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n elizaLogger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst remoteAttestationProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n elizaLogger.log(\"Generating attestation for: \", agentId);\n const attestation = await provider.generateAttestation(agentId, 'raw');\n return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`;\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n },\n};\n\nexport { remoteAttestationProvider, RemoteAttestationProvider };\n","export enum TEEMode {\n OFF = \"OFF\",\n LOCAL = \"LOCAL\", // For local development with simulator\n DOCKER = \"DOCKER\", // For docker development with simulator\n PRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n quote: string;\n timestamp: number;\n}\n","import {\n IAgentRuntime,\n Memory,\n Provider,\n State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { Keypair } from \"@solana/web3.js\";\nimport crypto from \"crypto\";\nimport { DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { PrivateKeyAccount, keccak256 } from \"viem\";\nimport { RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { TEEMode, RemoteAttestationQuote } from \"../types/tee\";\n\ninterface DeriveKeyAttestationData {\n agentId: string;\n publicKey: string;\n}\n\nclass DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n elizaLogger.log(\n \"Generating Remote Attestation Quote for Derive Key...\"\n );\n const quote = await this.raProvider.generateAttestation(reportdata);\n elizaLogger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n elizaLogger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n elizaLogger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n const hash = crypto.createHash(\"sha256\");\n hash.update(uint8ArrayDerivedKey);\n const seed = hash.digest();\n const seedArray = new Uint8Array(seed);\n const keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n elizaLogger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse =\n await this.client.deriveKey(path, subject);\n const hex = keccak256(deriveKeyResponse.asUint8Array());\n const keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n elizaLogger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\nconst deriveKeyProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new DeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n elizaLogger.error(\n \"Wallet secret salt is not configured in settings\"\n );\n return \"\";\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n \"/\",\n secretSalt,\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n \"/\",\n secretSalt,\n agentId\n );\n return JSON.stringify({\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n });\n } catch (error) {\n elizaLogger.error(\"Error creating PublicKey:\", error);\n return \"\";\n }\n } catch (error) {\n elizaLogger.error(\"Error in derive key provider:\", error.message);\n return `Failed to fetch derive key information: ${error instanceof Error ? error.message : \"Unknown error\"}`;\n }\n },\n};\n\nexport { deriveKeyProvider, DeriveKeyProvider };\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount(\n source: accountSource,\n): GetAccountReturnType {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters): SerializeSignatureReturnType {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType\n return hexToBytes(signature) as SerializeSignatureReturnType\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters): Promise> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray = T | readonly RecursiveArray[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp(\n bytes: RecursiveArray | RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType\n return cursor.bytes as ToRlpReturnType\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp(\n bytes: RecursiveArray,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp(\n hex: RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray | RecursiveArray,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization(\n parameters: HashAuthorizationParameters,\n): HashAuthorizationReturnType {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType\n return hash as HashAuthorizationReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters,\n): BlobsToCommitmentsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters,\n): blobsToProofsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType\n}\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\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 Sha256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash\n return toHex(bytes) as Sha256Hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters,\n): CommitmentToVersionedHashReturnType {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters,\n): CommitmentsToVersionedHashesReturnType {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters): ToBlobsReturnType {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType =\n | (to extends 'bytes' ? BlobSidecars : never)\n | (to extends 'hex' ? BlobSidecars : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters,\n): ToBlobSidecarsReturnType {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract\n : never),\n> = IsNever extends true\n ? string\n : IsNever extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType {\n if (transaction.type)\n return transaction.type as GetTransactionType\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial,\n ExactPartial &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = TransactionSerialized>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n>(\n parameters: SignTransactionParameters,\n): Promise> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n typeof domain?.chainId === 'number' && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record\n },\n results: Set = new Set(),\n): Set {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters,\n): Promise {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import type { IAgentRuntime, Memory, State, HandlerCallback } from \"@elizaos/core\";\nimport { RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { fetch, type BodyInit } from \"undici\";\n\nfunction hexToUint8Array(hex: string) {\n hex = hex.trim();\n if (!hex) {\n throw new Error(\"Invalid hex string\");\n }\n if (hex.startsWith(\"0x\")) {\n hex = hex.substring(2);\n }\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n const byte = parseInt(hex.slice(i, i + 2), 16);\n if (isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, 'quote.bin');\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\nexport const remoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n description: \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n _message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback,\n ) => {\n try {\n // Get the remote attestation of the agentId\n const agentId = runtime.agentId;\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const attestation = await provider.generateAttestation(agentId, 'raw');\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n callback({\n text: `Here's my 🧾 RA Quote 🫡\n https://proof.t16z.com/reports/${data.checksum}`,\n action: \"NONE\",\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n user: \"{{user1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n },\n },\n {\n user: \"{{user2}}\",\n content: {\n text: \"Of course, one second...\",\n action: \"REMOTE_ATTESTATION\",\n },\n }\n ],\n ],\n};","import { Plugin } from \"@elizaos/core\";\nimport { remoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nimport { deriveKeyProvider } from \"./providers/deriveKeyProvider\";\nimport { remoteAttestationAction } from \"./actions/remoteAttestation\";\n\nexport { DeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { RemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { RemoteAttestationQuote, TEEMode } from \"./types/tee\";\n\nexport const teePlugin: Plugin = {\n name: \"tee\",\n description:\n \"TEE plugin with actions to generate remote attestations and derive keys\",\n actions: [\n /* custom actions */\n remoteAttestationAction,\n ],\n evaluators: [\n /* custom evaluators */\n ],\n providers: [\n /* custom providers */\n remoteAttestationProvider,\n deriveKeyProvider,\n ],\n services: [\n /* custom services */\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKI;AAAA,OACG;AACP,SAA2B,mBAA2C;;;ACP/D,IAAK,UAAL,kBAAKA,aAAL;AACH,EAAAA,SAAA,SAAM;AACN,EAAAA,SAAA,WAAQ;AACR,EAAAA,SAAA,YAAS;AACT,EAAAA,SAAA,gBAAa;AAJL,SAAAA;AAAA,GAAA;;;ADUZ,IAAM,4BAAN,MAAgC;AAAA,EACpB;AAAA,EAER,YAAY,SAAkB;AAC1B,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACb;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,cAAM,IAAI;AAAA,UACN,qBAAqB,OAAO;AAAA,QAChC;AAAA,IACR;AAEA,SAAK,SAAS,WAAW,IAAI,YAAY,QAAQ,IAAI,IAAI,YAAY;AAAA,EACzE;AAAA,EAEA,MAAM,oBACF,YACA,eAC+B;AAC/B,QAAI;AACA,kBAAY,IAAI,gCAAgC,UAAU;AAC1D,YAAM,WACF,MAAM,KAAK,OAAO,SAAS,YAAY,aAAa;AACxD,YAAM,QAAQ,SAAS,YAAY;AACnC,kBAAY;AAAA,QACR,UAAU,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,MAClF;AACA,YAAM,QAAgC;AAAA,QAClC,OAAO,SAAS;AAAA,QAChB,WAAW,K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,EACA,WAAW;AAAA;AAAA,IAEP;AAAA,IACA;AAAA,EACJ;AAAA,EACA,UAAU;AAAA;AAAA,EAEV;AACJ;","names":["TEEMode","elizaLogger","TappdClient","sha256","toBytes","sha256","size","size","blobs","commitments","proofs","v","struct","elizaLogger","TappdClient"]} \ No newline at end of file diff --git a/dist/secp256k1-QUTB2QC2.js b/dist/secp256k1-QUTB2QC2.js new file mode 100644 index 0000000..0b1762d --- /dev/null +++ b/dist/secp256k1-QUTB2QC2.js @@ -0,0 +1,14 @@ +import { + encodeToCurve, + hashToCurve, + schnorr, + secp256k1 +} from "./chunk-4L6P6TY5.js"; +import "./chunk-PR4QN5HX.js"; +export { + encodeToCurve, + hashToCurve, + schnorr, + secp256k1 +}; +//# sourceMappingURL=secp256k1-QUTB2QC2.js.map \ No newline at end of file diff --git a/dist/secp256k1-QUTB2QC2.js.map b/dist/secp256k1-QUTB2QC2.js.map new file mode 100644 index 0000000..84c51b2 --- /dev/null +++ b/dist/secp256k1-QUTB2QC2.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file From 3fe69f6f8113026e292ebf8a2e1f276b2e7ed313 Mon Sep 17 00:00:00 2001 From: Carlos V Date: Mon, 27 Jan 2025 22:24:30 -0500 Subject: [PATCH 06/39] Update package.json --- package.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/package.json b/package.json index 58e2d94..6bacbf3 100644 --- a/package.json +++ b/package.json @@ -36,5 +36,25 @@ }, "peerDependencies": { "whatwg-url": "7.1.0" + }, + "agentConfig": { + "pluginType": "elizaos:client:1.0.0", + "pluginParameters": { + "TEE_MODE": { + "type": "string", + "enum": ["sgx", "nitro", "disabled"], + "description": "Trusted Execution Environment mode" + }, + "WALLET_SECRET_SALT": { + "type": "string", + "minLength": 1, + "description": "Salt for wallet secret generation" + }, + "BIRDEYE_API_KEY": { + "type": "string", + "minLength": 1, + "description": "API key for Birdeye service" + } + } } } From 9cd8b93c34bbdbfe028da8c767e5fae6cc34d7da Mon Sep 17 00:00:00 2001 From: Carlos V Date: Wed, 29 Jan 2025 20:52:46 -0500 Subject: [PATCH 07/39] fix: update package name to match repository name --- package.json | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 6bacbf3..1f4d524 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "@elizaos/plugin-tee", + "name": "@elizaos-plugins/plugin-tee", "version": "0.1.8+build.1", "type": "module", "main": "dist/index.js", @@ -42,7 +42,11 @@ "pluginParameters": { "TEE_MODE": { "type": "string", - "enum": ["sgx", "nitro", "disabled"], + "enum": [ + "sgx", + "nitro", + "disabled" + ], "description": "Trusted Execution Environment mode" }, "WALLET_SECRET_SALT": { @@ -57,4 +61,4 @@ } } } -} +} \ No newline at end of file From 7af50fd9c8110ae197b8760740ad87dd5be2defe Mon Sep 17 00:00:00 2001 From: Avaer Kazmer Date: Tue, 4 Feb 2025 23:49:30 -0800 Subject: [PATCH 08/39] Initial commit --- __tests__/deriveKey.test.ts | 111 +++++++++++++++++++ __tests__/remoteAttestation.test.ts | 81 ++++++++++++++ __tests__/remoteAttestationAction.test.ts | 103 ++++++++++++++++++ __tests__/timeout.test.ts | 117 +++++++++++++++++++++ biome.json | 41 ++++++++ eslint.config.mjs | 3 - package.json | 110 +++++++++---------- src/actions/remoteAttestation.ts | 25 +++-- src/index.ts | 2 +- src/providers/deriveKeyProvider.ts | 47 ++++++--- src/providers/remoteAttestationProvider.ts | 27 +++-- src/providers/walletProvider.ts | 14 +-- src/types/tee.ts | 16 +++ 13 files changed, 592 insertions(+), 105 deletions(-) create mode 100644 __tests__/deriveKey.test.ts create mode 100644 __tests__/remoteAttestation.test.ts create mode 100644 __tests__/remoteAttestationAction.test.ts create mode 100644 __tests__/timeout.test.ts create mode 100644 biome.json delete mode 100644 eslint.config.mjs diff --git a/__tests__/deriveKey.test.ts b/__tests__/deriveKey.test.ts new file mode 100644 index 0000000..deabae7 --- /dev/null +++ b/__tests__/deriveKey.test.ts @@ -0,0 +1,111 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { DeriveKeyProvider } from '../src/providers/deriveKeyProvider'; +import { TappdClient } from '@phala/dstack-sdk'; +import { TEEMode } from '../src/types/tee'; + +// Mock dependencies +vi.mock('@phala/dstack-sdk', () => ({ + TappdClient: vi.fn().mockImplementation(() => ({ + deriveKey: vi.fn().mockResolvedValue({ + asUint8Array: () => new Uint8Array([1, 2, 3, 4, 5]) + }), + tdxQuote: vi.fn().mockResolvedValue({ + quote: 'mock-quote-data', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] + }), + rawDeriveKey: vi.fn() + })) +})); + +vi.mock('@solana/web3.js', () => ({ + Keypair: { + fromSeed: vi.fn().mockReturnValue({ + publicKey: { + toBase58: () => 'mock-solana-public-key' + } + }) + } +})); + +vi.mock('viem/accounts', () => ({ + privateKeyToAccount: vi.fn().mockReturnValue({ + address: 'mock-evm-address' + }) +})); + +describe('DeriveKeyProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('constructor', () => { + it('should initialize with LOCAL mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + }); + + it('should initialize with DOCKER mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + }); + + it('should initialize with PRODUCTION mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.PRODUCTION); + expect(TappdClient).toHaveBeenCalledWith(); + }); + + it('should throw error for invalid mode', () => { + expect(() => new DeriveKeyProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + }); + }); + + describe('rawDeriveKey', () => { + let _provider: DeriveKeyProvider; + + beforeEach(() => { + _provider = new DeriveKeyProvider(TEEMode.LOCAL); + }); + + it('should derive raw key successfully', async () => { + const path = 'test-path'; + const subject = 'test-subject'; + const result = await _provider.rawDeriveKey(path, subject); + + const client = TappdClient.mock.results[0].value; + expect(client.deriveKey).toHaveBeenCalledWith(path, subject); + expect(result.asUint8Array()).toEqual(new Uint8Array([1, 2, 3, 4, 5])); + }); + + it('should handle errors during raw key derivation', async () => { + const mockError = new Error('Key derivation failed'); + vi.mocked(TappdClient).mockImplementationOnce(() => { + const instance = new TappdClient(); + instance.deriveKey = vi.fn().mockRejectedValueOnce(mockError); + instance.tdxQuote = vi.fn(); + instance.rawDeriveKey = vi.fn(); + return instance; + }); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(provider.rawDeriveKey('path', 'subject')).rejects.toThrow(mockError); + }); + }); + + describe('deriveEd25519Keypair', () => { + let provider: DeriveKeyProvider; + + beforeEach(() => { + provider = new DeriveKeyProvider(TEEMode.LOCAL); + }); + + it('should derive Ed25519 keypair successfully', async () => { + const path = 'test-path'; + const subject = 'test-subject'; + const result = await provider.deriveEd25519Keypair(path, subject); + + const client = TappdClient.mock.results[0].value; + expect(client.deriveKey).toHaveBeenCalledWith(path, subject); + expect(result.keypair.publicKey.toBase58()).toEqual('mock-solana-public-key'); + }); + }); +}); \ No newline at end of file diff --git a/__tests__/remoteAttestation.test.ts b/__tests__/remoteAttestation.test.ts new file mode 100644 index 0000000..4890d66 --- /dev/null +++ b/__tests__/remoteAttestation.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; +import { TappdClient } from '@phala/dstack-sdk'; +import { TEEMode } from '../src/types/tee'; + +// Mock TappdClient +vi.mock('@phala/dstack-sdk', () => ({ + TappdClient: vi.fn().mockImplementation(() => ({ + tdxQuote: vi.fn().mockResolvedValue({ + quote: 'mock-quote-data', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] + }), + deriveKey: vi.fn() + })) +})); + +describe('RemoteAttestationProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('constructor', () => { + it('should initialize with LOCAL mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + }); + + it('should initialize with DOCKER mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + }); + + it('should initialize with PRODUCTION mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.PRODUCTION); + expect(TappdClient).toHaveBeenCalledWith(); + }); + + it('should throw error for invalid mode', () => { + expect(() => new RemoteAttestationProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + }); + }); + + describe('generateAttestation', () => { + let provider: RemoteAttestationProvider; + + beforeEach(() => { + provider = new RemoteAttestationProvider(TEEMode.LOCAL); + }); + + it('should generate attestation successfully', async () => { + const reportData = 'test-report-data'; + const quote = await provider.generateAttestation(reportData); + + expect(quote).toEqual({ + quote: 'mock-quote-data', + timestamp: expect.any(Number) + }); + }); + + it('should handle errors during attestation generation', async () => { + const mockError = new Error('TDX Quote generation failed'); + const mockTdxQuote = vi.fn().mockRejectedValue(mockError); + vi.mocked(TappdClient).mockImplementationOnce(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn() + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(provider.generateAttestation('test-data')).rejects.toThrow('Failed to generate TDX Quote'); + }); + + it('should pass hash algorithm to tdxQuote when provided', async () => { + const reportData = 'test-report-data'; + const hashAlgorithm = 'raw'; + await provider.generateAttestation(reportData, hashAlgorithm); + + const client = TappdClient.mock.results[0].value; + expect(client.tdxQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); + }); + }); +}); \ No newline at end of file diff --git a/__tests__/remoteAttestationAction.test.ts b/__tests__/remoteAttestationAction.test.ts new file mode 100644 index 0000000..897de2c --- /dev/null +++ b/__tests__/remoteAttestationAction.test.ts @@ -0,0 +1,103 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { remoteAttestationAction } from '../src/actions/remoteAttestation'; +import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; + +// Mock dependencies +vi.mock('../src/providers/remoteAttestationProvider'); +vi.mock('undici', () => ({ + fetch: vi.fn().mockResolvedValue({ + json: () => Promise.resolve({ checksum: 'mock-checksum' }) + }) +})); + +describe('remoteAttestationAction', () => { + const mockRuntime = { + agentId: 'test-agent-id', + getSetting: vi.fn().mockReturnValue('LOCAL'), + getState: vi.fn(), + setState: vi.fn(), + message:{ userId: 'user', roomId: 'room', content: { text: 'If you are running in a TEE, generate a remote attestation' } }, + setConversation: vi.fn() + }; + + const mockCallback = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(RemoteAttestationProvider).mockImplementation(() => ({ + generateAttestation: vi.fn().mockResolvedValue({ + quote: '0x1234', + timestamp: Date.now() + }) + })); + }); + + it('should have correct name and similes', () => { + expect(remoteAttestationAction.name).toBe('REMOTE_ATTESTATION'); + expect(remoteAttestationAction.similes).toContain('REMOTE_ATTESTATION'); + expect(remoteAttestationAction.similes).toContain('TEE_REMOTE_ATTESTATION'); + expect(remoteAttestationAction.similes).toContain('TEE_ATTESTATION'); + }); + + describe('handler', () => { + it('should generate and upload attestation successfully', async () => { + const result = await remoteAttestationAction.handler( + mockRuntime, + mockRuntime.message, + {}, + {}, + mockCallback + ); + + expect(result).toBe(true); + expect(mockCallback).toHaveBeenCalledWith({ + text: expect.stringContaining('https://proof.t16z.com/reports/mock-checksum'), + action: 'NONE' + }); + }); + + it('should handle errors during attestation generation', async () => { + const mockError = new Error('Attestation generation failed'); + vi.mocked(RemoteAttestationProvider).mockImplementation(() => ({ + generateAttestation: vi.fn().mockRejectedValueOnce(mockError), + client: { + tdxQuote: vi.fn(), + deriveKey: vi.fn() + } + })); + + const result = await remoteAttestationAction.handler( + mockRuntime, + {}, + {}, + {}, + mockCallback + ); + + expect(result).toBe(false); + }); + }); + + describe('validate', () => { + it('should always return true', async () => { + const result = await remoteAttestationAction.validate(mockRuntime); + expect(result).toBe(true); + }); + }); + + describe('examples', () => { + it('should have valid example conversations', () => { + expect(remoteAttestationAction.examples).toBeInstanceOf(Array); + expect(remoteAttestationAction.examples[0]).toBeInstanceOf(Array); + + const [userMessage, agentMessage] = remoteAttestationAction.examples[0]; + expect(userMessage.user).toBe('{{user1}}'); + expect(userMessage.content.text).toBe('If you are running in a TEE, generate a remote attestation'); + expect(userMessage.content.action).toBe('REMOTE_ATTESTATION'); + + expect(agentMessage.user).toBe('{{user2}}'); + expect(agentMessage.content.text).toBe('Of course, one second...'); + expect(agentMessage.content.action).toBeUndefined(); + }); + }); +}); \ No newline at end of file diff --git a/__tests__/timeout.test.ts b/__tests__/timeout.test.ts new file mode 100644 index 0000000..f16a54d --- /dev/null +++ b/__tests__/timeout.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; +import { DeriveKeyProvider } from '../src/providers/deriveKeyProvider'; +import { TEEMode } from '../src/types/tee'; +import { TappdClient } from '@phala/dstack-sdk'; + +// Mock TappdClient +vi.mock('@phala/dstack-sdk', () => ({ + TappdClient: vi.fn().mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: vi.fn() + })) +})); + +describe('TEE Provider Timeout Tests', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('RemoteAttestationProvider', () => { + it('should handle API timeout during attestation generation', async () => { + const mockTdxQuote = vi.fn() + .mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn() + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => provider.generateAttestation('test-data')) + .rejects + .toThrow('Failed to generate TDX Quote: Request timed out'); + + // Verify the call was made once + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + expect(mockTdxQuote).toHaveBeenCalledWith('test-data', undefined); + }); + + it('should handle network errors during attestation generation', async () => { + const mockTdxQuote = vi.fn() + .mockRejectedValueOnce(new Error('Network error')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn() + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => provider.generateAttestation('test-data')) + .rejects + .toThrow('Failed to generate TDX Quote: Network error'); + + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + }); + + it('should handle successful attestation generation', async () => { + const mockQuote = { + quote: 'test-quote', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] + }; + + const mockTdxQuote = vi.fn().mockResolvedValueOnce(mockQuote); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn() + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + const result = await provider.generateAttestation('test-data'); + + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + expect(result).toEqual({ + quote: 'test-quote', + timestamp: expect.any(Number) + }); + }); + }); + + describe('DeriveKeyProvider', () => { + it('should handle API timeout during key derivation', async () => { + const mockDeriveKey = vi.fn() + .mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: mockDeriveKey + })); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(() => provider.rawDeriveKey('test-path', 'test-subject')) + .rejects + .toThrow('Request timed out'); + + expect(mockDeriveKey).toHaveBeenCalledTimes(1); + expect(mockDeriveKey).toHaveBeenCalledWith('test-path', 'test-subject'); + }); + + it('should handle API timeout during Ed25519 key derivation', async () => { + const mockDeriveKey = vi.fn() + .mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: mockDeriveKey + })); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(() => provider.deriveEd25519Keypair('test-path', 'test-subject')) + .rejects + .toThrow('Request timed out'); + + expect(mockDeriveKey).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..818716a --- /dev/null +++ b/biome.json @@ -0,0 +1,41 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.5.3/schema.json", + "organizeImports": { + "enabled": false + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "correctness": { + "noUnusedVariables": "error" + }, + "suspicious": { + "noExplicitAny": "error" + }, + "style": { + "useConst": "error", + "useImportType": "off" + } + } + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 4, + "lineWidth": 100 + }, + "javascript": { + "formatter": { + "quoteStyle": "single", + "trailingCommas": "es5" + } + }, + "files": { + "ignore": [ + "dist/**/*", + "extra/**/*", + "node_modules/**/*" + ] + } +} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs deleted file mode 100644 index 92fe5bb..0000000 --- a/eslint.config.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import eslintGlobalConfig from "../../eslint.config.mjs"; - -export default [...eslintGlobalConfig]; diff --git a/package.json b/package.json index 1f4d524..9744bd5 100644 --- a/package.json +++ b/package.json @@ -1,64 +1,48 @@ { - "name": "@elizaos-plugins/plugin-tee", - "version": "0.1.8+build.1", - "type": "module", - "main": "dist/index.js", - "module": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - "./package.json": "./package.json", - ".": { - "import": { - "@elizaos/source": "./src/index.ts", - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } - } - }, - "files": [ - "dist" - ], - "dependencies": { - "@elizaos/core": "workspace:*", - "@phala/dstack-sdk": "0.1.7", - "@solana/spl-token": "0.4.9", - "@solana/web3.js": "1.95.8", - "bignumber.js": "9.1.2", - "bs58": "6.0.0", - "node-cache": "5.1.2", - "pumpdotfun-sdk": "1.3.2", - "tsup": "8.3.5" - }, - "scripts": { - "build": "tsup --format esm --dts", - "dev": "tsup --format esm --dts --watch", - "lint": "eslint --fix --cache ." - }, - "peerDependencies": { - "whatwg-url": "7.1.0" - }, - "agentConfig": { - "pluginType": "elizaos:client:1.0.0", - "pluginParameters": { - "TEE_MODE": { - "type": "string", - "enum": [ - "sgx", - "nitro", - "disabled" - ], - "description": "Trusted Execution Environment mode" - }, - "WALLET_SECRET_SALT": { - "type": "string", - "minLength": 1, - "description": "Salt for wallet secret generation" - }, - "BIRDEYE_API_KEY": { - "type": "string", - "minLength": 1, - "description": "API key for Birdeye service" - } - } - } -} \ No newline at end of file + "name": "@elizaos/plugin-tee", + "version": "0.1.9", + "type": "module", + "main": "dist/index.js", + "module": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "@elizaos/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "dependencies": { + "@elizaos/core": "workspace:*", + "@phala/dstack-sdk": "0.1.7", + "@solana/spl-token": "0.4.9", + "@solana/web3.js": "1.95.8", + "bignumber.js": "9.1.2", + "bs58": "6.0.0", + "node-cache": "5.1.2", + "pumpdotfun-sdk": "1.3.2", + "tsup": "8.3.5" + }, + "devDependencies": { + "@biomejs/biome": "1.5.3", + "tsup": "^8.3.5" + }, + "scripts": { + "build": "tsup --format esm --dts", + "dev": "tsup --format esm --dts --watch", + "test": "vitest run", + "lint": "biome check src/", + "lint:fix": "biome check --apply src/", + "format": "biome format src/", + "format:fix": "biome format --write src/" + }, + "peerDependencies": { + "whatwg-url": "7.1.0" + } +} diff --git a/src/actions/remoteAttestation.ts b/src/actions/remoteAttestation.ts index f1fddbd..dd80e05 100644 --- a/src/actions/remoteAttestation.ts +++ b/src/actions/remoteAttestation.ts @@ -1,6 +1,7 @@ import type { IAgentRuntime, Memory, State, HandlerCallback } from "@elizaos/core"; import { RemoteAttestationProvider } from "../providers/remoteAttestationProvider"; import { fetch, type BodyInit } from "undici"; +import type { RemoteAttestationMessage } from "../types/tee"; function hexToUint8Array(hex: string) { hex = hex.trim(); @@ -16,7 +17,7 @@ function hexToUint8Array(hex: string) { const array = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) { - const byte = parseInt(hex.slice(i, i + 2), 16); + const byte = Number.parseInt(hex.slice(i, i + 2), 16); if (isNaN(byte)) { throw new Error("Invalid hex string"); } @@ -42,23 +43,33 @@ export const remoteAttestationAction = { description: "Generate a remote attestation to prove that the agent is running in a TEE", handler: async ( runtime: IAgentRuntime, - _message: Memory, + message: Memory, _state: State, _options: { [key: string]: unknown }, callback: HandlerCallback, ) => { try { + // Attestation will be generated based on the message info + const attestationMessage: RemoteAttestationMessage = { + agentId: runtime.agentId, + timestamp: Date.now(), + message: { + userId: message.userId, + roomId: message.roomId, + content: message.content.text, + }, + }; // Get the remote attestation of the agentId - const agentId = runtime.agentId; const teeMode = runtime.getSetting("TEE_MODE"); const provider = new RemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation(agentId, 'raw'); + + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); const attestationData = hexToUint8Array(attestation.quote); const response = await uploadUint8Array(attestationData); const data = await response.json(); callback({ text: `Here's my 🧾 RA Quote 🫡 - https://proof.t16z.com/reports/${data.checksum}`, +https://proof.t16z.com/reports/${data.checksum}`, action: "NONE", }); return true; @@ -76,15 +87,15 @@ export const remoteAttestationAction = { user: "{{user1}}", content: { text: "If you are running in a TEE, generate a remote attestation", + action: "REMOTE_ATTESTATION", }, }, { user: "{{user2}}", content: { text: "Of course, one second...", - action: "REMOTE_ATTESTATION", }, } ], ], -}; \ No newline at end of file +}; diff --git a/src/index.ts b/src/index.ts index 4ebc26b..09880da 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { Plugin } from "@elizaos/core"; +import type { Plugin } from "@elizaos/core"; import { remoteAttestationProvider } from "./providers/remoteAttestationProvider"; import { deriveKeyProvider } from "./providers/deriveKeyProvider"; import { remoteAttestationAction } from "./actions/remoteAttestation"; diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index 96430f2..8c533ad 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -1,22 +1,17 @@ import { - IAgentRuntime, - Memory, - Provider, - State, + type IAgentRuntime, + type Memory, + type Provider, + type State, elizaLogger, } from "@elizaos/core"; import { Keypair } from "@solana/web3.js"; import crypto from "crypto"; -import { DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; +import { type DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; import { privateKeyToAccount } from "viem/accounts"; -import { PrivateKeyAccount, keccak256 } from "viem"; +import { type PrivateKeyAccount, keccak256 } from "viem"; import { RemoteAttestationProvider } from "./remoteAttestationProvider"; -import { TEEMode, RemoteAttestationQuote } from "../types/tee"; - -interface DeriveKeyAttestationData { - agentId: string; - publicKey: string; -} +import { TEEMode, type RemoteAttestationQuote, type DeriveKeyAttestationData } from "../types/tee"; class DeriveKeyProvider { private client: TappdClient; @@ -57,11 +52,13 @@ class DeriveKeyProvider { private async generateDeriveKeyAttestation( agentId: string, - publicKey: string + publicKey: string, + subject?: string ): Promise { const deriveKeyData: DeriveKeyAttestationData = { agentId, publicKey, + subject, }; const reportdata = JSON.stringify(deriveKeyData); elizaLogger.log( @@ -72,6 +69,12 @@ class DeriveKeyProvider { return quote; } + /** + * Derives a raw key from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @returns The derived key. + */ async rawDeriveKey( path: string, subject: string @@ -94,6 +97,13 @@ class DeriveKeyProvider { } } + /** + * Derives an Ed25519 keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. + * @returns An object containing the derived keypair and attestation. + */ async deriveEd25519Keypair( path: string, subject: string, @@ -130,6 +140,13 @@ class DeriveKeyProvider { } } + /** + * Derives an ECDSA keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. + * @returns An object containing the derived keypair and attestation. + */ async deriveEcdsaKeypair( path: string, subject: string, @@ -184,13 +201,13 @@ const deriveKeyProvider: Provider = { const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; const solanaKeypair = await provider.deriveEd25519Keypair( - "/", secretSalt, + "solana", agentId ); const evmKeypair = await provider.deriveEcdsaKeypair( - "/", secretSalt, + "evm", agentId ); return JSON.stringify({ diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts index 262b58c..478ff26 100644 --- a/src/providers/remoteAttestationProvider.ts +++ b/src/providers/remoteAttestationProvider.ts @@ -1,12 +1,12 @@ import { - IAgentRuntime, - Memory, - Provider, - State, + type IAgentRuntime, + type Memory, + type Provider, + type State, elizaLogger, } from "@elizaos/core"; -import { TdxQuoteResponse, TappdClient, TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; -import { RemoteAttestationQuote, TEEMode } from "../types/tee"; +import { type TdxQuoteResponse, TappdClient, type TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; +import { type RemoteAttestationQuote, TEEMode, type RemoteAttestationMessage } from "../types/tee"; class RemoteAttestationProvider { private client: TappdClient; @@ -74,14 +74,23 @@ class RemoteAttestationProvider { // Keep the original provider for backwards compatibility const remoteAttestationProvider: Provider = { - get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => { + get: async (runtime: IAgentRuntime, message: Memory, _state?: State) => { const teeMode = runtime.getSetting("TEE_MODE"); const provider = new RemoteAttestationProvider(teeMode); const agentId = runtime.agentId; try { - elizaLogger.log("Generating attestation for: ", agentId); - const attestation = await provider.generateAttestation(agentId, 'raw'); + const attestationMessage: RemoteAttestationMessage = { + agentId: agentId, + timestamp: Date.now(), + message: { + userId: message.userId, + roomId: message.roomId, + content: message.content.text, + } + }; + elizaLogger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; } catch (error) { console.error("Error in remote attestation provider:", error); diff --git a/src/providers/walletProvider.ts b/src/providers/walletProvider.ts index a31cc65..5177a7d 100644 --- a/src/providers/walletProvider.ts +++ b/src/providers/walletProvider.ts @@ -1,16 +1,16 @@ /* This is an example of how WalletProvider can use DeriveKeyProvider to generate a Solana Keypair */ import { - IAgentRuntime, - Memory, - Provider, - State, + type IAgentRuntime, + type Memory, + type Provider, + type State, elizaLogger, } from "@elizaos/core"; -import { Connection, Keypair, PublicKey } from "@solana/web3.js"; +import { Connection, type Keypair, type PublicKey } from "@solana/web3.js"; import BigNumber from "bignumber.js"; import NodeCache from "node-cache"; import { DeriveKeyProvider } from "./deriveKeyProvider"; -import { RemoteAttestationQuote } from "../types/tee"; +import type { RemoteAttestationQuote } from "../types/tee"; // Provider configuration const PROVIDER_CONFIG = { BIRDEYE_API: "https://public-api.birdeye.so", @@ -299,8 +299,8 @@ const walletProvider: Provider = { keypair: Keypair; attestation: RemoteAttestationQuote; } = await deriveKeyProvider.deriveEd25519Keypair( - "/", runtime.getSetting("WALLET_SECRET_SALT"), + "solana", agentId ); publicKey = derivedKeyPair.keypair.publicKey; diff --git a/src/types/tee.ts b/src/types/tee.ts index de974c3..9e3ae1f 100644 --- a/src/types/tee.ts +++ b/src/types/tee.ts @@ -9,3 +9,19 @@ export interface RemoteAttestationQuote { quote: string; timestamp: number; } + +export interface DeriveKeyAttestationData { + agentId: string; + publicKey: string; + subject?: string; +} + +export interface RemoteAttestationMessage { + agentId: string; + timestamp: number; + message: { + userId: string; + roomId: string; + content: string; + } +} \ No newline at end of file From c735c1e5c60621f3d8ef30eebf3c1473f46a4935 Mon Sep 17 00:00:00 2001 From: Avaer Kazmer Date: Tue, 4 Feb 2025 23:49:30 -0800 Subject: [PATCH 09/39] Build --- dist/{ccip-IAE5UWYX.js => ccip-MMGH6DXX.js} | 4 +- ...p-IAE5UWYX.js.map => ccip-MMGH6DXX.js.map} | 0 dist/chunk-KSHJJL6X.js.map | 1 - dist/{chunk-KSHJJL6X.js => chunk-NTU6R7BC.js} | 36 +++++----- dist/chunk-NTU6R7BC.js.map | 1 + dist/index.d.ts | 20 ++++++ dist/index.js | 70 ++++++++++++++----- dist/index.js.map | 2 +- 8 files changed, 96 insertions(+), 38 deletions(-) rename dist/{ccip-IAE5UWYX.js => ccip-MMGH6DXX.js} (75%) rename dist/{ccip-IAE5UWYX.js.map => ccip-MMGH6DXX.js.map} (100%) delete mode 100644 dist/chunk-KSHJJL6X.js.map rename dist/{chunk-KSHJJL6X.js => chunk-NTU6R7BC.js} (98%) create mode 100644 dist/chunk-NTU6R7BC.js.map diff --git a/dist/ccip-IAE5UWYX.js b/dist/ccip-MMGH6DXX.js similarity index 75% rename from dist/ccip-IAE5UWYX.js rename to dist/ccip-MMGH6DXX.js index 1893f40..95194f6 100644 --- a/dist/ccip-IAE5UWYX.js +++ b/dist/ccip-MMGH6DXX.js @@ -3,7 +3,7 @@ import { offchainLookup, offchainLookupAbiItem, offchainLookupSignature -} from "./chunk-KSHJJL6X.js"; +} from "./chunk-NTU6R7BC.js"; import "./chunk-PR4QN5HX.js"; export { ccipRequest, @@ -11,4 +11,4 @@ export { offchainLookupAbiItem, offchainLookupSignature }; -//# sourceMappingURL=ccip-IAE5UWYX.js.map \ No newline at end of file +//# sourceMappingURL=ccip-MMGH6DXX.js.map \ No newline at end of file diff --git a/dist/ccip-IAE5UWYX.js.map b/dist/ccip-MMGH6DXX.js.map similarity index 100% rename from dist/ccip-IAE5UWYX.js.map rename to dist/ccip-MMGH6DXX.js.map diff --git a/dist/chunk-KSHJJL6X.js.map b/dist/chunk-KSHJJL6X.js.map deleted file mode 100644 index 7f6eac6..0000000 --- a/dist/chunk-KSHJJL6X.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../node_modules/abitype/src/version.ts","../../../node_modules/abitype/src/errors.ts","../../../node_modules/abitype/src/regex.ts","../../../node_modules/abitype/src/human-readable/formatAbiParameter.ts","../../../node_modules/abitype/src/human-readable/formatAbiParameters.ts","../../../node_modules/abitype/src/human-readable/formatAbiItem.ts","../../../node_modules/abitype/src/human-readable/runtime/signatures.ts","../../../node_modules/abitype/src/human-readable/errors/abiItem.ts","../../../node_modules/abitype/src/human-readable/errors/abiParameter.ts","../../../node_modules/abitype/src/human-readable/errors/signature.ts","../../../node_modules/abitype/src/human-readable/errors/struct.ts","../../../node_modules/abitype/src/human-readable/errors/splitParameters.ts","../../../node_modules/abitype/src/human-readable/runtime/cache.ts","../../../node_modules/abitype/src/human-readable/runtime/utils.ts","../../../node_modules/abitype/src/human-readable/runtime/structs.ts","../../../node_modules/abitype/src/human-readable/parseAbi.ts","../../../node_modules/viem/accounts/utils/parseAccount.ts","../../../node_modules/viem/constants/abis.ts","../../../node_modules/viem/constants/contract.ts","../../../node_modules/viem/constants/contracts.ts","../../../node_modules/viem/errors/version.ts","../../../node_modules/viem/errors/base.ts","../../../node_modules/viem/errors/chain.ts","../../../node_modules/viem/constants/solidity.ts","../../../node_modules/viem/utils/abi/formatAbiItem.ts","../../../node_modules/viem/utils/data/isHex.ts","../../../node_modules/viem/utils/data/size.ts","../../../node_modules/viem/errors/abi.ts","../../../node_modules/viem/errors/data.ts","../../../node_modules/viem/utils/data/slice.ts","../../../node_modules/viem/utils/data/pad.ts","../../../node_modules/viem/errors/encoding.ts","../../../node_modules/viem/utils/data/trim.ts","../../../node_modules/viem/utils/encoding/fromHex.ts","../../../node_modules/viem/utils/encoding/toHex.ts","../../../node_modules/viem/utils/encoding/toBytes.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/viem/utils/hash/keccak256.ts","../../../node_modules/viem/utils/hash/hashSignature.ts","../../../node_modules/viem/utils/hash/normalizeSignature.ts","../../../node_modules/viem/utils/hash/toSignature.ts","../../../node_modules/viem/utils/hash/toSignatureHash.ts","../../../node_modules/viem/utils/hash/toFunctionSelector.ts","../../../node_modules/viem/errors/address.ts","../../../node_modules/viem/utils/lru.ts","../../../node_modules/viem/utils/address/isAddress.ts","../../../node_modules/viem/utils/address/getAddress.ts","../../../node_modules/viem/errors/cursor.ts","../../../node_modules/viem/utils/cursor.ts","../../../node_modules/viem/utils/encoding/fromBytes.ts","../../../node_modules/viem/utils/data/concat.ts","../../../node_modules/viem/utils/regex.ts","../../../node_modules/viem/utils/abi/encodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeErrorResult.ts","../../../node_modules/viem/utils/stringify.ts","../../../node_modules/viem/utils/hash/toEventSelector.ts","../../../node_modules/viem/utils/abi/getAbiItem.ts","../../../node_modules/viem/constants/unit.ts","../../../node_modules/viem/utils/unit/formatUnits.ts","../../../node_modules/viem/utils/unit/formatEther.ts","../../../node_modules/viem/utils/unit/formatGwei.ts","../../../node_modules/viem/errors/stateOverride.ts","../../../node_modules/viem/errors/transaction.ts","../../../node_modules/viem/errors/utils.ts","../../../node_modules/viem/errors/contract.ts","../../../node_modules/viem/utils/abi/decodeFunctionResult.ts","../../../node_modules/viem/utils/abi/encodeDeployData.ts","../../../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../../../node_modules/viem/utils/abi/encodeFunctionData.ts","../../../node_modules/viem/utils/chain/getChainContractAddress.ts","../../../node_modules/viem/errors/node.ts","../../../node_modules/viem/errors/request.ts","../../../node_modules/viem/utils/errors/getNodeError.ts","../../../node_modules/viem/utils/errors/getCallError.ts","../../../node_modules/viem/utils/formatters/extract.ts","../../../node_modules/viem/utils/formatters/transactionRequest.ts","../../../node_modules/viem/utils/promise/withResolvers.ts","../../../node_modules/viem/utils/promise/createBatchScheduler.ts","../../../node_modules/viem/utils/stateOverride.ts","../../../node_modules/viem/constants/number.ts","../../../node_modules/viem/utils/transaction/assertRequest.ts","../../../node_modules/viem/actions/public/call.ts","../../../node_modules/viem/errors/ccip.ts","../../../node_modules/viem/utils/address/isAddressEqual.ts","../../../node_modules/viem/utils/ccip.ts"],"sourcesContent":["export const version = '1.0.7'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n\n override name = 'AbiTypeError'\n\n constructor(shortMessage: string, args: BaseErrorArgs = {}) {\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 const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: abitype@${version}`,\n ].join('\\n')\n\n super(message)\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","// 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 type | 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 abiParameter - 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 abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter 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 [key in keyof components]: FormatAbiParameter<\n {\n type: components[key]['type']\n } & (IsNarrowable extends true\n ? { name: components[key]['name'] }\n : unknown) &\n (components[key] extends { components: readonly AbiParameter[] }\n ? { components: components[key]['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 : `${abiParameter['type']}${abiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${abiParameter['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 abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): 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 abiParameters - 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [key in keyof abiParameters]: 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: abiParameters): 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 {\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 abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem =\n Abi[number] extends abiItem\n ? string\n :\n | (abiItem extends AbiFunction\n ? AbiFunction extends abiItem\n ? string\n : `function ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${abiItem['stateMutability']}`\n : ''}${abiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters})`}`\n : never)\n | (abiItem extends AbiEvent\n ? AbiEvent extends abiItem\n ? string\n : `event ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiError\n ? AbiError extends abiItem\n ? string\n : `error ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiConstructor\n ? AbiConstructor extends abiItem\n ? string\n : `constructor(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiFallback\n ? AbiFallback extends abiItem\n ? string\n : `fallback() external${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiReceive\n ? AbiReceive extends abiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? abiParameters\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: abiItem,\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 if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n if (abiItem.type === 'fallback')\n return `fallback() external${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }` as Result\n return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n EventModifier,\n FunctionModifier,\n Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n errorSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isEventSignature(signature: string) {\n return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n eventSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n return execTyped<{\n name: string\n parameters: string\n stateMutability?: AbiStateMutability\n returns?: string\n }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?.*?)\\}$/\nexport function isStructSignature(signature: string) {\n return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n return execTyped<{ name: string; properties: string }>(\n structSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n /^constructor\\((?.*?)\\)(?:\\s(?payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex =\n /^fallback\\(\\) external(?:\\s(?payable{1}))?$/\nexport function isFallbackSignature(signature: string) {\n return fallbackSignatureRegex.test(signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set([\n 'memory',\n 'indexed',\n 'storage',\n 'calldata',\n])\nexport const eventModifiers = new Set(['indexed'])\nexport const functionModifiers = new Set([\n 'calldata',\n 'memory',\n 'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n override name = 'InvalidAbiItemError'\n\n constructor({ signature }: { signature: string | object }) {\n super('Failed to parse ABI item.', {\n details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n docsPath: '/api/human#parseabiitem-1',\n })\n }\n}\n\nexport class UnknownTypeError extends BaseError {\n override name = 'UnknownTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [\n `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n ],\n })\n }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n override name = 'UnknownSolidityTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n override name = 'InvalidAbiParameterError'\n\n constructor({ param }: { param: string | object }) {\n super('Failed to parse ABI parameter.', {\n details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n docsPath: '/api/human#parseabiparameter-1',\n })\n }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n override name = 'InvalidAbiParametersError'\n\n constructor({ params }: { params: string | object }) {\n super('Failed to parse ABI parameters.', {\n details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n docsPath: '/api/human#parseabiparameters-1',\n })\n }\n}\n\nexport class InvalidParameterError extends BaseError {\n override name = 'InvalidParameterError'\n\n constructor({ param }: { param: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n })\n }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n override name = 'SolidityProtectedKeywordError'\n\n constructor({ param, name }: { param: string; name: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n ],\n })\n }\n}\n\nexport class InvalidModifierError extends BaseError {\n override name = 'InvalidModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n ],\n })\n }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n override name = 'InvalidFunctionModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n ],\n })\n }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n override name = 'InvalidAbiTypeParameterError'\n\n constructor({\n abiParameter,\n }: {\n abiParameter: AbiParameter & { indexed?: boolean | undefined }\n }) {\n super('Invalid ABI parameter.', {\n details: JSON.stringify(abiParameter, null, 2),\n metaMessages: ['ABI parameter type is invalid.'],\n })\n }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n override name = 'InvalidSignatureError'\n\n constructor({\n signature,\n type,\n }: {\n signature: string\n type: AbiItemType | 'struct'\n }) {\n super(`Invalid ${type} signature.`, {\n details: signature,\n })\n }\n}\n\nexport class UnknownSignatureError extends BaseError {\n override name = 'UnknownSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Unknown signature.', {\n details: signature,\n })\n }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n override name = 'InvalidStructSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Invalid struct signature.', {\n details: signature,\n metaMessages: ['No properties exist.'],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n override name = 'CircularReferenceError'\n\n constructor({ type }: { type: string }) {\n super('Circular reference detected.', {\n metaMessages: [`Struct \"${type}\" is a circular reference.`],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n override name = 'InvalidParenthesisError'\n\n constructor({ current, depth }: { current: string; depth: number }) {\n super('Unbalanced parentheses.', {\n metaMessages: [\n `\"${current.trim()}\" has too many ${\n depth > 0 ? 'opening' : 'closing'\n } parentheses.`,\n ],\n details: `Depth \"${depth}\"`,\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport type { StructLookup } from '../types/structs.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n param: string,\n type?: AbiItemType | 'struct',\n structs?: StructLookup,\n) {\n let structKey = ''\n if (structs)\n for (const struct of Object.entries(structs)) {\n if (!struct) continue\n let propertyKey = ''\n for (const property of struct[1]) {\n propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`\n }\n structKey += `(${struct[0]}{${propertyKey}})`\n }\n if (type) return `${type}:${param}${structKey}`\n return param\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n string,\n AbiParameter & { indexed?: boolean }\n>([\n // Unnamed\n ['address', { type: 'address' }],\n ['bool', { type: 'bool' }],\n ['bytes', { type: 'bytes' }],\n ['bytes32', { type: 'bytes32' }],\n ['int', { type: 'int256' }],\n ['int256', { type: 'int256' }],\n ['string', { type: 'string' }],\n ['uint', { type: 'uint256' }],\n ['uint8', { type: 'uint8' }],\n ['uint16', { type: 'uint16' }],\n ['uint24', { type: 'uint24' }],\n ['uint32', { type: 'uint32' }],\n ['uint64', { type: 'uint64' }],\n ['uint96', { type: 'uint96' }],\n ['uint112', { type: 'uint112' }],\n ['uint160', { type: 'uint160' }],\n ['uint192', { type: 'uint192' }],\n ['uint256', { type: 'uint256' }],\n\n // Named\n ['address owner', { type: 'address', name: 'owner' }],\n ['address to', { type: 'address', name: 'to' }],\n ['bool approved', { type: 'bool', name: 'approved' }],\n ['bytes _data', { type: 'bytes', name: '_data' }],\n ['bytes data', { type: 'bytes', name: 'data' }],\n ['bytes signature', { type: 'bytes', name: 'signature' }],\n ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n ['bytes32 r', { type: 'bytes32', name: 'r' }],\n ['bytes32 root', { type: 'bytes32', name: 'root' }],\n ['bytes32 s', { type: 'bytes32', name: 's' }],\n ['string name', { type: 'string', name: 'name' }],\n ['string symbol', { type: 'string', name: 'symbol' }],\n ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint8 v', { type: 'uint8', name: 'v' }],\n ['uint256 balance', { type: 'uint256', name: 'balance' }],\n ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint256 value', { type: 'uint256', name: 'value' }],\n\n // Indexed\n [\n 'event:address indexed from',\n { type: 'address', name: 'from', indexed: true },\n ],\n ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n [\n 'event:uint indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n [\n 'event:uint256 indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n])\n","import type {\n AbiItemType,\n AbiType,\n SolidityArray,\n SolidityBytes,\n SolidityString,\n SolidityTuple,\n} from '../../abi.js'\nimport {\n bytesRegex,\n execTyped,\n integerRegex,\n isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n eventModifiers,\n execConstructorSignature,\n execErrorSignature,\n execEventSignature,\n execFunctionSignature,\n functionModifiers,\n isConstructorSignature,\n isErrorSignature,\n isEventSignature,\n isFallbackSignature,\n isFunctionSignature,\n isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n if (isFunctionSignature(signature)) {\n const match = execFunctionSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n const inputParams = splitParameters(match.parameters)\n const inputs = []\n const inputLength = inputParams.length\n for (let i = 0; i < inputLength; i++) {\n inputs.push(\n parseAbiParameter(inputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n\n const outputs = []\n if (match.returns) {\n const outputParams = splitParameters(match.returns)\n const outputLength = outputParams.length\n for (let i = 0; i < outputLength; i++) {\n outputs.push(\n parseAbiParameter(outputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n }\n\n return {\n name: match.name,\n type: 'function',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs,\n outputs,\n }\n }\n\n if (isEventSignature(signature)) {\n const match = execEventSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, {\n modifiers: eventModifiers,\n structs,\n type: 'event',\n }),\n )\n }\n return { name: match.name, type: 'event', inputs: abiParameters }\n }\n\n if (isErrorSignature(signature)) {\n const match = execErrorSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'error' }),\n )\n }\n return { name: match.name, type: 'error', inputs: abiParameters }\n }\n\n if (isConstructorSignature(signature)) {\n const match = execConstructorSignature(signature)\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n )\n }\n return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n }\n\n if (isFallbackSignature(signature)) return { type: 'fallback' }\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n /^\\((?.+?)\\)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n modifiers?: Set\n structs?: StructLookup\n type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n // optional namespace cache by `type`\n const parameterCacheKey = getParameterCacheKey(\n param,\n options?.type,\n options?.structs,\n )\n if (parameterCache.has(parameterCacheKey))\n return parameterCache.get(parameterCacheKey)!\n\n const isTuple = isTupleRegex.test(param)\n const match = execTyped<{\n array?: string\n modifier?: Modifier\n name?: string\n type: string\n }>(\n isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n param,\n )\n if (!match) throw new InvalidParameterError({ param })\n\n if (match.name && isSolidityKeyword(match.name))\n throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n const name = match.name ? { name: match.name } : {}\n const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n const structs = options?.structs ?? {}\n let type: string\n let components = {}\n if (isTuple) {\n type = 'tuple'\n const params = splitParameters(match.type)\n const components_ = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n // remove `modifiers` from `options` to prevent from being added to tuple components\n components_.push(parseAbiParameter(params[i]!, { structs }))\n }\n components = { components: components_ }\n } else if (match.type in structs) {\n type = 'tuple'\n components = { components: structs[match.type] }\n } else if (dynamicIntegerRegex.test(match.type)) {\n type = `${match.type}256`\n } else {\n type = match.type\n if (!(options?.type === 'struct') && !isSolidityType(type))\n throw new UnknownSolidityTypeError({ type })\n }\n\n if (match.modifier) {\n // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n if (!options?.modifiers?.has?.(match.modifier))\n throw new InvalidModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n\n // Check if resolved `type` is valid if there is a function modifier\n if (\n functionModifiers.has(match.modifier as FunctionModifier) &&\n !isValidDataLocation(type, !!match.array)\n )\n throw new InvalidFunctionModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n }\n\n const abiParameter = {\n type: `${type}${match.array ?? ''}`,\n ...name,\n ...indexed,\n ...components,\n }\n parameterCache.set(parameterCacheKey, abiParameter)\n return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n params: string,\n result: string[] = [],\n current = '',\n depth = 0,\n): readonly string[] {\n const length = params.trim().length\n // biome-ignore lint/correctness/noUnreachable: recursive\n for (let i = 0; i < length; i++) {\n const char = params[i]\n const tail = params.slice(i + 1)\n switch (char) {\n case ',':\n return depth === 0\n ? splitParameters(tail, [...result, current.trim()])\n : splitParameters(tail, result, `${current}${char}`, depth)\n case '(':\n return splitParameters(tail, result, `${current}${char}`, depth + 1)\n case ')':\n return splitParameters(tail, result, `${current}${char}`, depth - 1)\n default:\n return splitParameters(tail, result, `${current}${char}`, depth)\n }\n }\n\n if (current === '') return result\n if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n result.push(current.trim())\n return result\n}\n\nexport function isSolidityType(\n type: string,\n): type is Exclude {\n return (\n type === 'address' ||\n type === 'bool' ||\n type === 'function' ||\n type === 'string' ||\n bytesRegex.test(type) ||\n integerRegex.test(type)\n )\n}\n\nconst protectedKeywordsRegex =\n /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\n/** @internal */\nexport function isSolidityKeyword(name: string) {\n return (\n name === 'address' ||\n name === 'bool' ||\n name === 'function' ||\n name === 'string' ||\n name === 'tuple' ||\n bytesRegex.test(name) ||\n integerRegex.test(name) ||\n protectedKeywordsRegex.test(name)\n )\n}\n\n/** @internal */\nexport function isValidDataLocation(\n type: string,\n isArray: boolean,\n): type is Exclude<\n AbiType,\n SolidityString | Extract | SolidityArray\n> {\n return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n const shallowStructs: StructLookup = {}\n const signaturesLength = signatures.length\n for (let i = 0; i < signaturesLength; i++) {\n const signature = signatures[i]!\n if (!isStructSignature(signature)) continue\n\n const match = execStructSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n const properties = match.properties.split(';')\n\n const components: AbiParameter[] = []\n const propertiesLength = properties.length\n for (let k = 0; k < propertiesLength; k++) {\n const property = properties[k]!\n const trimmed = property.trim()\n if (!trimmed) continue\n const abiParameter = parseAbiParameter(trimmed, {\n type: 'struct',\n })\n components.push(abiParameter)\n }\n\n if (!components.length) throw new InvalidStructSignatureError({ signature })\n shallowStructs[match.name] = components\n }\n\n // Resolve nested structs inside each parameter\n const resolvedStructs: StructLookup = {}\n const entries = Object.entries(shallowStructs)\n const entriesLength = entries.length\n for (let i = 0; i < entriesLength; i++) {\n const [name, parameters] = entries[i]!\n resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n }\n\n return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n abiParameters: readonly (AbiParameter & { indexed?: true })[],\n structs: StructLookup,\n ancestors = new Set(),\n) {\n const components: AbiParameter[] = []\n const length = abiParameters.length\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i]!\n const isTuple = isTupleRegex.test(abiParameter.type)\n if (isTuple) components.push(abiParameter)\n else {\n const match = execTyped<{ array?: string; type: string }>(\n typeWithoutTupleRegex,\n abiParameter.type,\n )\n if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n const { array, type } = match\n if (type in structs) {\n if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n components.push({\n ...abiParameter,\n type: `tuple${array ?? ''}`,\n components: resolveStructs(\n structs[type] ?? [],\n structs,\n new Set([...ancestors, type]),\n ),\n })\n } else {\n if (isSolidityType(type)) components.push(abiParameter)\n else throw new UnknownTypeError({ type })\n }\n }\n }\n\n return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Error, Filter } from '../types.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * type Result = ParseAbi<\n * // ^? type Result = readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * [\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ]\n * >\n */\nexport type ParseAbi =\n string[] extends signatures\n ? Abi // If `T` was not able to be inferred (e.g. just `string[]`), return `Abi`\n : signatures extends readonly string[]\n ? signatures extends Signatures // Validate signatures\n ? ParseStructs extends infer sructs\n ? {\n [key in keyof signatures]: signatures[key] extends string\n ? ParseSignature\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends infer result\n ? result extends readonly []\n ? never\n : result\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n * // ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi(\n signatures: signatures['length'] extends 0\n ? Error<'At least one signature required'>\n : Signatures extends signatures\n ? signatures\n : Signatures,\n): ParseAbi {\n const structs = parseStructs(signatures as readonly string[])\n const abi = []\n const length = signatures.length as number\n for (let i = 0; i < length; i++) {\n const signature = (signatures as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n abi.push(parseSignature(signature, structs))\n }\n return abi as unknown as ParseAbi\n}\n","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(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\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 {\n inputs: [],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n components: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'errors',\n type: 'tuple[]',\n },\n ],\n name: 'HttpError',\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 {\n name: 'resolve',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n { name: 'gateways', type: 'string[]' },\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 {\n name: 'reverse',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'string[]', name: 'gateways' },\n ],\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\n/** @internal */\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 name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n] as const\n\n/** [ERC-20 Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) */\nexport const erc20Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/**\n * [bytes32-flavored ERC-20](https://docs.makerdao.com/smart-contract-modules/mkr-module#4.-gotchas-potential-source-of-user-error)\n * for tokens (ie. Maker) that use bytes32 instead of string.\n */\nexport const erc20Abi_bytes32 = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/** [ERC-721 Non-Fungible Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) */\nexport const erc721Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'ApprovalForAll',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n name: 'approved',\n type: 'bool',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'getApproved',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'isApprovedForAll',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'operator',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'ownerOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'id',\n type: 'uint256',\n },\n {\n name: 'data',\n type: 'bytes',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'setApprovalForAll',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'operator',\n type: 'address',\n },\n {\n name: 'approved',\n type: 'bool',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenURI',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'tokeId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n] as const\n\n/** [ERC-4626 Tokenized Vaults Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-4626) */\nexport const erc4626Abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Deposit',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n name: 'allowance',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'approve',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'asset',\n outputs: [\n {\n name: 'assetTokenAddress',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'convertToAssets',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'convertToShares',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'deposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxDeposit',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxMint',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxRedeem',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxWithdraw',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'mint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewDeposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewMint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewRedeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewWithdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'redeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalAssets',\n outputs: [\n {\n name: 'totalManagedAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transfer',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transferFrom',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'withdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","export const aggregate3Signature = '0x82ad56cb'\n","export const deploylessCallViaBytecodeBytecode =\n '0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe'\n\nexport const deploylessCallViaFactoryBytecode =\n '0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe'\n\nexport const universalSignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n","export const version = '2.21.58'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\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(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (\n err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined\n )\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 constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint | undefined\n chain: Chain\n contract: { name: string; blockCreated?: number | undefined }\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 name: 'ChainDoesNotSupportContract',\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\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 name: 'ChainMismatchError',\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\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 name: 'ChainNotFoundError',\n },\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n })\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n { name: 'InvalidChainIdError' },\n )\n }\n}\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: 'Arithmetic 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","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 | undefined } = {},\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 | undefined } = {},\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 { 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 | undefined } = {},\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 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 type { Abi, 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 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 name: 'AbiConstructorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\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 name: 'AbiConstructorParamsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\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 {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\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 name: 'AbiDecodingDataSizeTooSmallError',\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 constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n })\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingArrayLengthMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\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 { name: 'AbiEncodingBytesSizeMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingLengthMismatchError' },\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\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 name: 'AbiErrorInputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(\n errorName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiErrorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\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 name: 'AbiErrorSignatureNotFoundError',\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\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 name: 'AbiEventSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(\n eventName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiEventNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(\n functionName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiFunctionNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\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 name: 'AbiFunctionOutputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\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 name: 'AbiFunctionSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(\n x: { abiItem: Abi[number]; type: string },\n y: { abiItem: Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n })\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n })\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\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 name: 'DecodeLogDataMismatch',\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 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 { name: 'DecodeLogTopicsMismatch' },\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\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, name: 'InvalidAbiEncodingType' },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\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, name: 'InvalidAbiDecodingType' },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n })\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\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 { name: 'InvalidDefinitionTypeError' },\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\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 { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\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 { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\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()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\n )\n }\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 = value 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: value,\n start?: number | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined) {\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(\n value: Hex | ByteArray,\n start?: number | undefined,\n end?: number | undefined,\n) {\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 {\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' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: value,\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 { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\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 { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\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 name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\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 { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim(\n hexOrBytes: value,\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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to 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\n * - Example: https://viem.sh/docs/utilities/fromHex#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 to 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 | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 | undefined\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#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#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 | undefined\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#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 {\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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toHex#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 | undefined\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#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 | undefined\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#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 | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\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#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: bigint | number | undefined\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${(\n signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : 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 | undefined\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#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 { 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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toBytes#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 | undefined\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#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 | undefined\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#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#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(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\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#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","function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n// TODO: re-check https://issues.chromium.org/issues/42212588\n\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { abytes, aexists, anumber, aoutput } 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 isLE,\n byteSwap32,\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: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: 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 anumber(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 if (!isLE) byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE) byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input) {\n aexists(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 aexists(this, false);\n abytes(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 anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array) {\n aoutput(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 | (to extends 'bytes' ? ByteArray : never)\n | (to 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_?: to | undefined,\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 ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport function hashSignature(sig: string) {\n return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype 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 AbiEvent, 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 ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n const def_ = (() => {\n if (typeof def === 'string') return def\n return formatAbiItem(def)\n })()\n return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n | HashSignatureErrorType\n | ToSignatureErrorType\n | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n return hashSignature(toSignature(fn))\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToFunctionSelectorErrorType =\n | ToSignatureHashErrorType\n | SliceErrorType\n | ErrorType\n\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn: string | AbiFunction) =>\n slice(toSignatureHash(fn), 0, 4)\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\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 { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap
(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\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 const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n })\n }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n { name: 'PositionOutOfBoundsError' },\n )\n }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n RecursiveReadLimitExceededError & {\n name: 'RecursiveReadLimitExceededError'\n }\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n { name: 'RecursiveReadLimitExceededError' },\n )\n }\n}\n","import {\n NegativeOffsetError,\n type NegativeOffsetErrorType,\n PositionOutOfBoundsError,\n type PositionOutOfBoundsErrorType,\n RecursiveReadLimitExceededError,\n type RecursiveReadLimitExceededErrorType,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n bytes: ByteArray\n dataView: DataView\n position: number\n positionReadCount: Map\n recursiveReadCount: number\n recursiveReadLimit: number\n remaining: number\n assertReadLimit(position?: number): void\n assertPosition(position: number): void\n decrementPosition(offset: number): void\n getReadCount(position?: number): number\n incrementPosition(offset: number): void\n inspectByte(position?: number): ByteArray[number]\n inspectBytes(length: number, position?: number): ByteArray\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: ByteArray[number]): void\n pushBytes(bytes: ByteArray): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): ByteArray[number]\n readBytes(length: number, size?: number): ByteArray\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\n\ntype CursorErrorType =\n | CursorAssertPositionErrorType\n | CursorDecrementPositionErrorType\n | CursorIncrementPositionErrorType\n | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype StaticCursorErrorType =\n | NegativeOffsetErrorType\n | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n })\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n })\n },\n decrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position - offset\n this.assertPosition(position)\n this.position = position\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0\n },\n incrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position + offset\n this.assertPosition(position)\n this.position = position\n },\n inspectByte(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + length - 1)\n return this.bytes.subarray(position, position + length)\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 1)\n return this.dataView.getUint16(position)\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 2)\n return (\n (this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2)\n )\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 3)\n return this.dataView.getUint32(position)\n },\n pushByte(byte: ByteArray[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: ByteArray) {\n this.assertPosition(this.position + bytes.length - 1)\n this.bytes.set(bytes, this.position)\n this.position += bytes.length\n },\n pushUint8(value: number) {\n this.assertPosition(this.position)\n this.bytes[this.position] = value\n this.position++\n },\n pushUint16(value: number) {\n this.assertPosition(this.position + 1)\n this.dataView.setUint16(this.position, value)\n this.position += 2\n },\n pushUint24(value: number) {\n this.assertPosition(this.position + 2)\n this.dataView.setUint16(this.position, value >> 8)\n this.dataView.setUint8(this.position + 2, value & ~4294967040)\n this.position += 3\n },\n pushUint32(value: number) {\n this.assertPosition(this.position + 3)\n this.dataView.setUint32(this.position, value)\n this.position += 4\n },\n readByte() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectByte()\n this.position++\n return value\n },\n readBytes(length, size) {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectBytes(length)\n this.position += size ?? length\n return value\n },\n readUint8() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint8()\n this.position += 1\n return value\n },\n readUint16() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint16()\n this.position += 2\n return value\n },\n readUint24() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint24()\n this.position += 3\n return value\n },\n readUint32() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint32()\n this.position += 4\n return value\n },\n get remaining() {\n return this.bytes.length - this.position\n },\n setPosition(position) {\n const oldPosition = this.position\n this.assertPosition(position)\n this.position = position\n return () => (this.position = oldPosition)\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n const count = this.getReadCount()\n this.positionReadCount.set(this.position, count + 1)\n if (count > 0) this.recursiveReadCount++\n },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n | CursorErrorType\n | StaticCursorErrorType\n | ErrorType\n\nexport function createCursor(\n bytes: ByteArray,\n { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n type AssertSizeErrorType,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n assertSize,\n hexToBigInt,\n hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n | to\n | {\n /** Size of the bytes. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromBytesReturnType = to extends 'string'\n ? string\n : to extends 'hex'\n ? Hex\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromBytesErrorType =\n | BytesToHexErrorType\n | BytesToBigIntErrorType\n | BytesToBoolErrorType\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n bytes: ByteArray,\n toOrOpts: FromBytesParameters,\n): FromBytesReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number')\n return bytesToNumber(bytes, opts) as FromBytesReturnType\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts) as FromBytesReturnType\n if (to === 'boolean')\n return bytesToBool(bytes, opts) as FromBytesReturnType\n if (to === 'string')\n return bytesToString(bytes, opts) as FromBytesReturnType\n return bytesToHex(bytes, opts) as FromBytesReturnType\n}\n\nexport type BytesToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n | BytesToHexErrorType\n | HexToBigIntErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n bytes: ByteArray,\n opts: BytesToBigIntOpts = {},\n): bigint {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n bytes_: ByteArray,\n opts: BytesToBoolOpts = {},\n): boolean {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes)\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes)\n return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n | BytesToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n bytes: ByteArray,\n opts: BytesToNumberOpts = {},\n): number {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n bytes_: ByteArray,\n opts: BytesToStringOpts = {},\n): string {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat(\n values: readonly value[],\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","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\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","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 { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.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'\nimport { integerRegex } from '../regex.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 *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: params,\n values: params 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 as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values: values as any,\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\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams({\n params,\n values,\n}: {\n params: params\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\ntype PrepareParamErrorType =\n | EncodeAddressErrorType\n | EncodeArrayErrorType\n | EncodeBytesErrorType\n | EncodeBoolErrorType\n | EncodeNumberErrorType\n | EncodeStringErrorType\n | EncodeTupleErrorType\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam({\n param,\n value,\n}: {\n param: param\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 const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\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\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | 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\ntype 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\ntype EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray(\n value: AbiParameterToPrimitiveType,\n {\n length,\n param,\n }: {\n length: number | null\n param: param\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\ntype EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes(\n value: Hex,\n { param }: { param: param },\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 !== Number.parseInt(paramSize))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n if (typeof value !== 'boolean')\n throw new BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\ntype 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\ntype EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType,\n { param }: { param: param },\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\ntype 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 { AbiParameter, AbiParametersToPrimitiveTypes } from 'abitype'\n\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type BytesToBigIntErrorType,\n type BytesToBoolErrorType,\n type BytesToNumberErrorType,\n type BytesToStringErrorType,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n params extends readonly AbiParameter[] ? params : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | DecodeParameterErrorType\n | SizeErrorType\n | CreateCursorErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const params extends readonly AbiParameter[],\n>(\n params: params,\n data: ByteArray | Hex,\n): DecodeAbiParametersReturnType {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data\n const cursor = createCursor(bytes)\n\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n\n let consumed = 0\n const values = []\n for (let i = 0; i < params.length; ++i) {\n const param = params[i]\n cursor.setPosition(consumed)\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n })\n consumed += consumed_\n values.push(data)\n }\n return values as DecodeAbiParametersReturnType\n}\n\ntype DecodeParameterErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeStringErrorType\n | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n if (param.type === 'address') return decodeAddress(cursor)\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | BytesToHexErrorType\n | SliceBytesErrorType\n | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n const value = cursor.readBytes(32)\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n cursor: Cursor,\n param: AbiParameter,\n { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 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 // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n | BytesToNumberErrorType\n | BytesToHexErrorType\n | ErrorType\n\nfunction decodeBytes(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [bytesToHex(data), 32]\n }\n\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size), 32))\n return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n | BytesToNumberErrorType\n | BytesToBigIntErrorType\n | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256')\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n cursor: Cursor,\n param: TupleAbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\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 // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\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 [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(\n cursor: Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = bytesToString(trim(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\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 } 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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n ContractErrorArgs,\n ContractErrorName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { slice } from '../data/slice.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = { abi?: abi | undefined; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allErrorNames extends ContractErrorName = ContractErrorName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [errorName in allErrorNames]: {\n abiItem: abi extends Abi\n ? Abi extends abi\n ? AbiItem\n : ExtractAbiError\n : AbiItem\n args: ContractErrorArgs\n errorName: errorName\n }\n }[allErrorNames]\n >\n : {\n abiItem: AbiItem\n args: readonly unknown[] | undefined\n errorName: string\n }\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult(\n parameters: DecodeErrorResultParameters,\n): DecodeErrorResultReturnType {\n const { abi, data } = parameters as DecodeErrorResultParameters\n\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...(abi || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args:\n 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType\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 type { ErrorType } from '../../errors/utils.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport {\n AbiItemAmbiguityError,\n type AbiItemAmbiguityErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ExtractAbiItemForArgs,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nexport type GetAbiItemParameters<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n ///\n allArgs = AbiItemArgs,\n allNames = AbiItemName,\n> = {\n abi: abi\n name:\n | allNames // show all options\n | (name extends allNames ? name : never) // infer value\n | Hex // function selector\n} & UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | ToFunctionSelectorErrorType\n | AbiItemAmbiguityErrorType\n | ErrorType\n\nexport type GetAbiItemReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n> = abi extends Abi\n ? Abi extends abi\n ? AbiItem | undefined\n : ExtractAbiItemForArgs<\n abi,\n name,\n args extends AbiItemArgs ? args : AbiItemArgs\n >\n : AbiItem | undefined\n\nexport function getAbiItem<\n const abi extends Abi | readonly unknown[],\n name extends AbiItemName,\n const args extends AbiItemArgs | undefined = undefined,\n>(\n parameters: GetAbiItemParameters,\n): GetAbiItemReturnType {\n const { abi, args = [], name } = parameters as unknown as GetAbiItemParameters\n\n const isSelector = isHex(name, { strict: false })\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return toEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0)\n return undefined as GetAbiItemReturnType\n if (abiItems.length === 1)\n return abiItems[0] as GetAbiItemReturnType\n\n let matchedAbiItem: AbiItem | undefined = undefined\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)\n return abiItem as GetAbiItemReturnType\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.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, abiParameter)\n })\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (\n matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs\n ) {\n const ambiguousTypes = getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AbiItemAmbiguityError(\n {\n abiItem,\n type: ambiguousTypes[0],\n },\n {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1],\n },\n )\n }\n\n matchedAbiItem = abiItem\n }\n }\n\n if (matchedAbiItem)\n return matchedAbiItem as GetAbiItemReturnType\n return abiItems[0] as GetAbiItemReturnType\n}\n\ntype IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\n/** @internal */\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, { strict: false })\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\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameter[],\n targetParameters: readonly AbiParameter[],\n args: AbiItemArgs,\n): AbiParameter['type'][] | undefined {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex]\n const targetParameter = targetParameters[parameterIndex]\n\n if (\n sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter\n )\n return getAmbiguousTypes(\n sourceParameter.components,\n targetParameter.components,\n (args as any)[parameterIndex],\n )\n\n const types = [sourceParameter.type, targetParameter.type]\n\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20')) return true\n if (types.includes('address') && types.includes('string'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\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 { 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\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","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\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\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 { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { BaseError } from './base.js'\n\nexport type AccountStateConflictErrorType = AccountStateConflictError & {\n name: 'AccountStateConflictError'\n}\n\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n })\n }\n}\n\nexport type StateAssignmentConflictErrorType = StateAssignmentConflictError & {\n name: 'StateAssignmentConflictError'\n}\n\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n })\n }\n}\n\n/** @internal */\nexport function prettyStateMapping(stateMapping: StateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`\n }, '')\n}\n\nexport function prettyStateOverride(stateOverride: StateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`\n if (state.nonce) val += ` nonce: ${state.nonce}\\n`\n if (state.balance) val += ` balance: ${state.balance}\\n`\n if (state.code) val += ` code: ${state.code}\\n`\n if (state.state) {\n val += ' state:\\n'\n val += prettyStateMapping(state.state)\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n'\n val += prettyStateMapping(state.stateDiff)\n }\n return val\n }, ' State Override:\\n')\n .slice(0, -1)\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 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 { name: 'FeeConflictError' },\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n })\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\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 '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n })\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\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 name: 'InvalidSerializedTransactionError',\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 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 { name: 'InvalidStorageKeySizeError' },\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'TransactionExecutionError',\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n blockTag?: BlockTag | undefined\n hash?: Hash | undefined\n index?: number | undefined\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 name: 'TransactionNotFoundError',\n })\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\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 name: 'TransactionReceiptNotFoundError',\n },\n )\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n { name: 'WaitForTransactionReceiptTimeoutError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nexport type ErrorType = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\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 { prettyStateOverride } from './stateOverride.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 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 stateOverride,\n }: CallParameters & {\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n let 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 if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`\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 name: 'CallExecutionError',\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[] | undefined\n override cause: BaseError\n contractAddress?: Address | undefined\n formattedArgs?: string | undefined\n functionName: string\n sender?: Address | undefined\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 | undefined\n contractAddress?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\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 prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'ContractFunctionExecutionError',\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 data?: DecodeErrorResultReturnType | undefined\n reason?: string | undefined\n signature?: Hex | undefined\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: {\n abi: Abi\n data?: Hex | undefined\n functionName: string\n message?: string | undefined\n }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined = undefined\n let metaMessages: string[] | undefined\n let reason: string | undefined\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 name: 'ContractFunctionRevertedError',\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 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 name: 'ContractFunctionZeroDataError',\n })\n }\n}\n\nexport type CounterfactualDeploymentFailedErrorType =\n CounterfactualDeploymentFailedError & {\n name: 'CounterfactualDeploymentFailedError'\n }\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }: { factory?: Address | undefined }) {\n super(\n `Deployment for counterfactual contract call failed${\n factory ? ` for factory \"${factory}\".` : ''\n }`,\n {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n },\n )\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n\n data?: Hex | { data?: Hex | undefined } | undefined\n\n constructor({\n data,\n message,\n }: {\n data?: Hex | { data?: Hex | undefined } | undefined\n message?: string | undefined\n }) {\n super(message || '', { name: 'RawContractError' })\n this.data = data\n }\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n data: Hex\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | undefined }\n : { functionName: functionName | allFunctionNames }\n : { functionName?: functionName | allFunctionNames | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type DecodeFunctionResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n> = ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n args\n>\n\nexport type DecodeFunctionResultErrorType =\n | AbiFunctionNotFoundErrorType\n | AbiFunctionOutputsNotFoundErrorType\n | DecodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function decodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n const args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n>(\n parameters: DecodeFunctionResultParameters,\n): DecodeFunctionResultReturnType {\n const { abi, args, functionName, data } =\n parameters as DecodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, args, name: functionName })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\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)\n return values as DecodeFunctionResultReturnType\n if (values && values.length === 1)\n return values[0] as DecodeFunctionResultReturnType\n return undefined as DecodeFunctionResultReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n hasConstructor = abi extends Abi\n ? Abi extends abi\n ? true\n : [Extract] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractConstructorArgs,\n> = {\n abi: abi\n bytecode: Hex\n} & UnionEvaluate<\n hasConstructor extends false\n ? { args?: undefined }\n : readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n>\n\nexport type EncodeDeployDataReturnType = Hex\n\nexport type EncodeDeployDataErrorType =\n | AbiConstructorNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | ErrorType\n\nexport function encodeDeployData(\n parameters: EncodeDeployDataParameters,\n): EncodeDeployDataReturnType {\n const { abi, args, bytecode } = parameters as EncodeDeployDataParameters\n if (!args || args.length === 0) return bytecode\n\n const description = abi.find((x) => 'type' in x && x.type === 'constructor')\n if (!description) throw new AbiConstructorNotFoundError({ docsPath })\n if (!('inputs' in description))\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n if (!description.inputs || description.inputs.length === 0)\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n\n const data = encodeAbiParameters(description.inputs, args)\n return concatHex([bytecode, data!])\n}\n","import type {\n Abi,\n AbiStateMutability,\n ExtractAbiFunction,\n ExtractAbiFunctions,\n} from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionData'\n\nexport type PrepareEncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<{ args?: allArgs | undefined }> &\n (hasFunctions extends true ? unknown : never)\n\nexport type PrepareEncodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n> = {\n abi: abi extends Abi\n ? functionName extends ContractFunctionName\n ? [ExtractAbiFunction]\n : abi\n : Abi\n functionName: Hex\n}\n\nexport type PrepareEncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function prepareEncodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: PrepareEncodeFunctionDataParameters,\n): PrepareEncodeFunctionDataReturnType {\n const { abi, args, functionName } =\n parameters as PrepareEncodeFunctionDataParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n } as unknown as PrepareEncodeFunctionDataReturnType\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport type { AbiFunctionNotFoundErrorType } from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport type { FormatAbiItemErrorType } from './formatAbiItem.js'\nimport type { GetAbiItemErrorType } from './getAbiItem.js'\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js'\n\nexport type EncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | Hex\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionDataReturnType = Hex\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionDataParameters,\n): EncodeFunctionDataReturnType {\n const { args } = parameters as EncodeFunctionDataParameters\n\n const { abi, functionName } = (() => {\n if (\n parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x')\n )\n return parameters as { abi: Abi; functionName: Hex }\n return prepareEncodeFunctionData(parameters)\n })()\n\n const abiItem = abi[0]\n const signature = functionName\n\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\n : undefined\n return concatHex([signature, data ?? '0x'])\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 | undefined\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 { 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 constructor({\n cause,\n message,\n }: { cause?: BaseError | undefined; message?: string | undefined } = {}) {\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 name: 'ExecutionRevertedError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooHighError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooLowError',\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause, name: 'NonceTooHighError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\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, name: 'NonceTooLowError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause, name: 'NonceMaxValueError' },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage =\n /insufficient funds|exceeds transaction sender account balance/\n constructor({ cause }: { cause?: BaseError | undefined } = {}) {\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 name: 'InsufficientFundsError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\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 name: 'IntrinsicGasTooHighError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n name: 'IntrinsicGasTooLowError',\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 constructor({ cause }: { cause?: BaseError | undefined }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\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 constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\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 name: 'TipAboveFeeCapError',\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }: { cause?: BaseError | undefined }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\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 body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\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 constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; data?: unknown; 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 name: 'RpcRequestError',\n })\n this.code = error.code\n this.data = error.data\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\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 name: 'TimeoutError',\n })\n }\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'\nimport type { ExactPartial } from '../../types/utils.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 = ExactPartial<\n SendTransactionParameters\n>\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 =\n err instanceof BaseError\n ? err.walk(\n (e) =>\n (e as { code: number } | null | undefined)?.code ===\n ExecutionRevertedError.code,\n )\n : err\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\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 { 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 | undefined\n docsPath?: string | undefined\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","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'] | undefined },\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 { AuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { bytesToHex, numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n chain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n request: ExactPartial,\n) {\n const rpcRequest = {} as RpcTransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(\n request.authorizationList,\n )\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = (request.blobs as ByteArray[]).map((x) =>\n bytesToHex(x),\n )\n else rpcRequest.blobs = request.blobs\n }\n if (typeof request.data !== 'undefined') rpcRequest.data = request.data\n if (typeof request.from !== 'undefined') rpcRequest.from = request.from\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce)\n if (typeof request.to !== 'undefined') rpcRequest.to = request.to\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type]\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value)\n\n return rpcRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: AuthorizationList,\n): RpcAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n address: authorization.contractAddress,\n r: authorization.r,\n s: authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }) as any,\n ) as RpcAuthorizationList\n}\n","/** @internal */\nexport type PromiseWithResolvers = {\n promise: Promise\n resolve: (value: type | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\n/** @internal */\nexport function withResolvers(): PromiseWithResolvers {\n let resolve: PromiseWithResolvers['resolve'] = () => undefined\n let reject: PromiseWithResolvers['reject'] = () => undefined\n\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_\n reject = reject_\n })\n\n return { promise, resolve, reject }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type PromiseWithResolvers, withResolvers } from './withResolvers.js'\n\ntype Resolved = [\n result: returnType[number],\n results: returnType,\n]\n\ntype SchedulerItem = {\n args: unknown\n resolve: PromiseWithResolvers['resolve']\n reject: PromiseWithResolvers['reject']\n}\n\ntype BatchResultsCompareFn = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise>\n : (args: parameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\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 parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i]\n resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i]\n reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\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: parameters) {\n const { promise, resolve, reject } = withResolvers()\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, resolve, reject })\n return promise\n }\n\n setScheduler({ args, resolve, reject })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n InvalidBytesLengthError,\n type InvalidBytesLengthErrorType,\n} from '../errors/data.js'\nimport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from '../errors/stateOverride.js'\nimport type {\n RpcAccountStateOverride,\n RpcStateMapping,\n RpcStateOverride,\n} from '../types/rpc.js'\nimport type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { isAddress } from './address/isAddress.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\n\ntype SerializeStateMappingParameters = StateMapping | undefined\n\ntype SerializeStateMappingErrorType = InvalidBytesLengthErrorType\n\n/** @internal */\nexport function serializeStateMapping(\n stateMapping: SerializeStateMappingParameters,\n): RpcStateMapping | undefined {\n if (!stateMapping || stateMapping.length === 0) return undefined\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n })\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n })\n acc[slot] = value\n return acc\n }, {} as RpcStateMapping)\n}\n\ntype SerializeAccountStateOverrideParameters = Omit<\n StateOverride[number],\n 'address'\n>\n\ntype SerializeAccountStateOverrideErrorType =\n | NumberToHexErrorType\n | StateAssignmentConflictErrorType\n | SerializeStateMappingErrorType\n\n/** @internal */\nexport function serializeAccountStateOverride(\n parameters: SerializeAccountStateOverrideParameters,\n): RpcAccountStateOverride {\n const { balance, nonce, state, stateDiff, code } = parameters\n const rpcAccountStateOverride: RpcAccountStateOverride = {}\n if (code !== undefined) rpcAccountStateOverride.code = code\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance)\n if (nonce !== undefined) rpcAccountStateOverride.nonce = numberToHex(nonce)\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state)\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state) throw new StateAssignmentConflictError()\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff)\n }\n return rpcAccountStateOverride\n}\n\ntype SerializeStateOverrideParameters = StateOverride | undefined\n\nexport type SerializeStateOverrideErrorType =\n | InvalidAddressErrorType\n | AccountStateConflictErrorType\n | SerializeAccountStateOverrideErrorType\n\n/** @internal */\nexport function serializeStateOverride(\n parameters?: SerializeStateOverrideParameters,\n): RpcStateOverride | undefined {\n if (!parameters) return undefined\n const rpcStateOverride: RpcStateOverride = {}\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address })\n rpcStateOverride[address] = serializeAccountStateOverride(accountState)\n }\n return rpcStateOverride\n}\n","export const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { maxUint256 } from '../../constants/number.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 type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = ExactPartial<\n SendTransactionParameters\n>\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 > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import { type Address, parseAbi } 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 {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n} from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ChainDoesNotSupportContract,\n ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n CounterfactualDeploymentFailedError,\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 { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.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 {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type CallParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Whether or not to enable multicall batching on this call. */\n batch?: boolean | undefined\n /** Bytecode to perform the call on. */\n code?: Hex | undefined\n /** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). */\n factory?: Address | undefined\n /** Calldata to execute on the factory to deploy the contract. */\n factoryData?: Hex | undefined\n /** State overrides for the call. */\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedCall =\n FormattedTransactionRequest\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | ScheduleMulticallErrorType\n | RequestErrorType\n | ToDeploylessCallViaBytecodeDataErrorType\n | ToDeploylessCallViaFactoryDataErrorType\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\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 blobs,\n code,\n data: data_,\n factory,\n factoryData,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n stateOverride,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n if (code && (factory || factoryData))\n throw new BaseError(\n 'Cannot provide both `code` & `factory`/`factoryData` as parameters.',\n )\n if (code && to)\n throw new BaseError('Cannot provide both `code` & `to` as parameters.')\n\n // Check if the call is deployless via bytecode.\n const deploylessCallViaBytecode = code && data_\n // Check if the call is deployless via a factory.\n const deploylessCallViaFactory = factory && factoryData && to && data_\n const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory\n\n const data = (() => {\n if (deploylessCallViaBytecode)\n return toDeploylessCallViaBytecodeData({\n code,\n data: data_,\n })\n if (deploylessCallViaFactory)\n return toDeploylessCallViaFactoryData({\n data: data_,\n factory,\n factoryData,\n to,\n })\n return data_\n })()\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\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 blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to: deploylessCall ? undefined : to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) {\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: rpcStateOverride\n ? [\n request as ExactPartial,\n block,\n rpcStateOverride,\n ]\n : [request as ExactPartial, block],\n })\n if (response === '0x') return { data: undefined }\n return { data: response }\n } catch (err) {\n const data = getRevertErrorData(err)\n\n // Check for CCIP-Read offchain lookup signature.\n const { offchainLookup, offchainLookupSignature } = await import(\n '../../utils/ccip.js'\n )\n if (\n client.ccipRead !== false &&\n data?.slice(0, 10) === offchainLookupSignature &&\n to\n )\n return { data: await offchainLookup(client, { data, to }) }\n\n // Check for counterfactual deployment error.\n if (deploylessCall && data?.slice(0, 10) === '0x101bb98d')\n throw new CounterfactualDeploymentFailedError({ factory })\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 | undefined\n to: Address\n}\n\ntype 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\ntype ToDeploylessCallViaBytecodeDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaBytecodeData(parameters: {\n code: Hex\n data: Hex\n}) {\n const { code, data } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(bytes, bytes)']),\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [code, data],\n })\n}\n\ntype ToDeploylessCallViaFactoryDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaFactoryData(parameters: {\n data: Hex\n factory: Address\n factoryData: Hex\n to: Address\n}) {\n const { data, factory, factoryData, to } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(address, bytes, address, bytes)']),\n bytecode: deploylessCallViaFactoryBytecode,\n args: [to, data, factory, factoryData],\n })\n}\n\n/** @internal */\nexport type GetRevertErrorDataErrorType = ErrorType\n\n/** @internal */\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 { Address } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type OffchainLookupErrorType = OffchainLookupError & {\n name: 'OffchainLookupError'\n}\nexport class OffchainLookupError extends BaseError {\n constructor({\n callbackSelector,\n cause,\n data,\n extraData,\n sender,\n urls,\n }: {\n callbackSelector: Hex\n cause: BaseError\n data: Hex\n extraData: Hex\n sender: Address\n urls: readonly string[]\n }) {\n super(\n cause.shortMessage ||\n 'An error occurred while fetching for an offchain result.',\n {\n cause,\n metaMessages: [\n ...(cause.metaMessages || []),\n cause.metaMessages?.length ? '' : [],\n 'Offchain Gateway Call:',\n urls && [\n ' Gateway URL(s):',\n ...urls.map((url) => ` ${getUrl(url)}`),\n ],\n ` Sender: ${sender}`,\n ` Data: ${data}`,\n ` Callback selector: ${callbackSelector}`,\n ` Extra data: ${extraData}`,\n ].flat(),\n name: 'OffchainLookupError',\n },\n )\n }\n}\n\nexport type OffchainLookupResponseMalformedErrorType =\n OffchainLookupResponseMalformedError & {\n name: 'OffchainLookupResponseMalformedError'\n }\nexport class OffchainLookupResponseMalformedError extends BaseError {\n constructor({ result, url }: { result: any; url: string }) {\n super(\n 'Offchain gateway response is malformed. Response data must be a hex value.',\n {\n metaMessages: [\n `Gateway URL: ${getUrl(url)}`,\n `Response: ${stringify(result)}`,\n ],\n name: 'OffchainLookupResponseMalformedError',\n },\n )\n }\n}\n\n/** @internal */\nexport type OffchainLookupSenderMismatchErrorType =\n OffchainLookupSenderMismatchError & {\n name: 'OffchainLookupSenderMismatchError'\n }\nexport class OffchainLookupSenderMismatchError extends BaseError {\n constructor({ sender, to }: { sender: Address; to: Address }) {\n super(\n 'Reverted sender address does not match target contract address (`to`).',\n {\n metaMessages: [\n `Contract address: ${to}`,\n `OffchainLookup sender address: ${sender}`,\n ],\n name: 'OffchainLookupSenderMismatchError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { isAddress } from './isAddress.js'\n\nexport type IsAddressEqualReturnType = boolean\nexport type IsAddressEqualErrorType = InvalidAddressErrorType | ErrorType\n\nexport function isAddressEqual(a: Address, b: Address) {\n if (!isAddress(a, { strict: false }))\n throw new InvalidAddressError({ address: a })\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b })\n return a.toLowerCase() === b.toLowerCase()\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { BaseError } from '../errors/base.js'\nimport {\n OffchainLookupError,\n type OffchainLookupErrorType as OffchainLookupErrorType_,\n OffchainLookupResponseMalformedError,\n type OffchainLookupResponseMalformedErrorType,\n OffchainLookupSenderMismatchError,\n} from '../errors/ccip.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n} from '../errors/request.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\n\nimport type { Client } from '../clients/createClient.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport { decodeErrorResult } from './abi/decodeErrorResult.js'\nimport { encodeAbiParameters } from './abi/encodeAbiParameters.js'\nimport { isAddressEqual } from './address/isAddressEqual.js'\nimport { concat } from './data/concat.js'\nimport { isHex } from './data/isHex.js'\nimport { stringify } from './stringify.js'\n\nexport const offchainLookupSignature = '0x556f1830'\nexport const offchainLookupAbiItem = {\n name: 'OffchainLookup',\n type: 'error',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'urls',\n type: 'string[]',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n {\n name: 'callbackFunction',\n type: 'bytes4',\n },\n {\n name: 'extraData',\n type: 'bytes',\n },\n ],\n} as const satisfies Abi[number]\n\nexport type OffchainLookupErrorType = OffchainLookupErrorType_ | ErrorType\n\nexport async function offchainLookup(\n client: Client,\n {\n blockNumber,\n blockTag,\n data,\n to,\n }: Pick & {\n data: Hex\n to: Address\n },\n): Promise {\n const { args } = decodeErrorResult({\n data,\n abi: [offchainLookupAbiItem],\n })\n const [sender, urls, callData, callbackSelector, extraData] = args\n\n const { ccipRead } = client\n const ccipRequest_ =\n ccipRead && typeof ccipRead?.request === 'function'\n ? ccipRead.request\n : ccipRequest\n\n try {\n if (!isAddressEqual(to, sender))\n throw new OffchainLookupSenderMismatchError({ sender, to })\n\n const result = await ccipRequest_({ data: callData, sender, urls })\n\n const { data: data_ } = await call(client, {\n blockNumber,\n blockTag,\n data: concat([\n callbackSelector,\n encodeAbiParameters(\n [{ type: 'bytes' }, { type: 'bytes' }],\n [result, extraData],\n ),\n ]),\n to,\n } as CallParameters)\n\n return data_!\n } catch (err) {\n throw new OffchainLookupError({\n callbackSelector,\n cause: err as BaseError,\n data,\n extraData,\n sender,\n urls,\n })\n }\n}\n\nexport type CcipRequestParameters = {\n data: Hex\n sender: Address\n urls: readonly string[]\n}\n\nexport type CcipRequestReturnType = Hex\n\nexport type CcipRequestErrorType =\n | HttpRequestErrorType\n | OffchainLookupResponseMalformedErrorType\n | ErrorType\n\nexport async function ccipRequest({\n data,\n sender,\n urls,\n}: CcipRequestParameters): Promise {\n let error = new Error('An unknown error occurred.')\n\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i]\n const method = url.includes('{data}') ? 'GET' : 'POST'\n const body = method === 'POST' ? { data, sender } : undefined\n const headers: HeadersInit =\n method === 'POST' ? { 'Content-Type': 'application/json' } : {}\n\n try {\n const response = await fetch(\n url.replace('{sender}', sender).replace('{data}', data),\n {\n body: JSON.stringify(body),\n headers,\n method,\n },\n )\n\n let result: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n ) {\n result = (await response.json()).data\n } else {\n result = (await response.text()) as any\n }\n\n if (!response.ok) {\n error = new HttpRequestError({\n body,\n details: result?.error\n ? stringify(result.error)\n : response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n continue\n }\n\n if (!isHex(result)) {\n error = new OffchainLookupResponseMalformedError({\n result,\n url,\n })\n continue\n }\n\n return result\n } catch (err) {\n error = new HttpRequestError({\n body,\n details: (err as Error).message,\n url,\n })\n }\n }\n\n throw error\n}\n"],"mappings":";AAAO,IAAM,UAAU;;;ACUjB,IAAO,YAAP,MAAO,mBAAkB,MAAK;EAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,UAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,UAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,UAAM,UAAU;MACd,gBAAgB;MAChB;MACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;MACrD,GAAIA,YAAW,CAAC,4BAA4BA,SAAQ,EAAE,IAAI,CAAA;MAC1D,GAAI,UAAU,CAAC,YAAY,OAAO,EAAE,IAAI,CAAA;MACxC,oBAAoB,OAAO;MAC3B,KAAK,IAAI;AAEX,UAAM,OAAO;AA3Bf,WAAA,eAAA,MAAA,WAAA;;;;;;AACA,WAAA,eAAA,MAAA,YAAA;;;;;;AACA,WAAA,eAAA,MAAA,gBAAA;;;;;;AACA,WAAA,eAAA,MAAA,gBAAA;;;;;;AAES,WAAA,eAAA,MAAA,QAAA;;;;aAAO;;AAwBd,QAAI,KAAK;AAAO,WAAK,QAAQ,KAAK;AAClC,SAAK,UAAU;AACf,SAAK,WAAWA;AAChB,SAAK,eAAe,KAAK;AACzB,SAAK,eAAe;EACtB;;;;AC3CI,SAAU,UAAgB,OAAe,QAAc;AAC3D,QAAM,QAAQ,MAAM,KAAK,MAAM;AAC/B,SAAO,OAAO;AAChB;AAIO,IAAM,aAAa;AAInB,IAAM,eACX;AAEK,IAAM,eAAe;;;ACsC5B,IAAM,aAAa;AAYb,SAAU,mBAEd,cAA0B;AAG1B,MAAI,OAAO,aAAa;AACxB,MAAI,W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YAAY,EAChC,MACA,QACA,KAAI,GACkB;AACtB,MAAI,QAAQ,IAAI,MAAM,4BAA4B;AAElD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAClB,UAAM,SAAS,IAAI,SAAS,QAAQ,IAAI,QAAQ;AAChD,UAAM,OAAO,WAAW,SAAS,EAAE,MAAM,OAAM,IAAK;AACpD,UAAM,UACJ,WAAW,SAAS,EAAE,gBAAgB,mBAAkB,IAAK,CAAA;AAE/D,QAAI;AACF,YAAM,WAAW,MAAM,MACrB,IAAI,QAAQ,YAAY,MAAM,EAAE,QAAQ,UAAU,IAAI,GACtD;QACE,MAAM,KAAK,UAAU,IAAI;QACzB;QACA;OACD;AAGH,UAAI;AACJ,UACE,SAAS,QAAQ,IAAI,cAAc,GAAG,WAAW,kBAAkB,GACnE;AACA,kBAAU,MAAM,SAAS,KAAI,GAAI;MACnC,OAAO;AACL,iBAAU,MAAM,SAAS,KAAI;MAC/B;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,gBAAQ,IAAI,iBAAiB;UAC3B;UACA,SAAS,QAAQ,QACb,UAAU,OAAO,KAAK,IACtB,SAAS;UACb,SAAS,SAAS;UAClB,QAAQ,SAAS;UACjB;SACD;AACD;MACF;AAEA,UAAI,CAAC,MAAM,MAAM,GAAG;AAClB,gBAAQ,IAAI,qCAAqC;UAC/C;UACA;SACD;AACD;MACF;AAEA,aAAO;IACT,SAAS,KAAK;AACZ,cAAQ,IAAI,iBAAiB;QAC3B;QACA,SAAU,IAAc;QACxB;OACD;IACH;EACF;AAEA,QAAM;AACR;","names":["docsPath","version","docsPath","version","BaseError","docsPath","version","BaseError","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","BaseError","docsPath","BaseError","docsPath","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","size","BaseError","size","BaseError","size","size","size","encoder","BaseError","toBytes","toBytes","toBytes","toBytes","BaseError","BaseError","size","hash","BaseError","size","bytesRegex","integerRegex","size","integerRegex","length","BaseError","data","length","consumed","value","size","formatAbiItem","value","BaseError","BaseError","BaseError","BaseError","docsPath","BaseError","docsPath","docsPath","formatAbiItem","BaseError","BaseError","BaseError","docsPath","cause","formatted","args","split","BaseError","data","offchainLookup","offchainLookupSignature","args","size","BaseError"]} \ No newline at end of file diff --git a/dist/chunk-KSHJJL6X.js b/dist/chunk-NTU6R7BC.js similarity index 98% rename from dist/chunk-KSHJJL6X.js rename to dist/chunk-NTU6R7BC.js index c539aea..25786aa 100644 --- a/dist/chunk-KSHJJL6X.js +++ b/dist/chunk-NTU6R7BC.js @@ -1,7 +1,7 @@ -// ../../node_modules/abitype/dist/esm/version.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/version.js var version = "1.0.7"; -// ../../node_modules/abitype/dist/esm/errors.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/errors.js var BaseError = class _BaseError extends Error { constructor(shortMessage, args = {}) { const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; @@ -54,7 +54,7 @@ var BaseError = class _BaseError extends Error { } }; -// ../../node_modules/abitype/dist/esm/regex.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/regex.js function execTyped(regex, string) { const match = regex.exec(string); return match?.groups; @@ -63,7 +63,7 @@ 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)?$/; var isTupleRegex = /^\(.+?\).*?$/; -// ../../node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js var tupleRegex = /^tuple(?(\[(\d*)\])*)$/; function formatAbiParameter(abiParameter) { let type = abiParameter.type; @@ -90,7 +90,7 @@ function formatAbiParameter(abiParameter) { return type; } -// ../../node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js function formatAbiParameters(abiParameters) { let params = ""; const length = abiParameters.length; @@ -103,7 +103,7 @@ function formatAbiParameters(abiParameters) { return params; } -// ../../node_modules/abitype/dist/esm/human-readable/formatAbiItem.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiItem.js function formatAbiItem(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)})` : ""}`; @@ -118,7 +118,7 @@ function formatAbiItem(abiItem) { return "receive() external payable"; } -// ../../node_modules/abitype/dist/esm/human-readable/runtime/signatures.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/signatures.js var errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; function isErrorSignature(signature) { return errorSignatureRegex.test(signature); @@ -169,7 +169,7 @@ var functionModifiers = /* @__PURE__ */ new Set([ "storage" ]); -// ../../node_modules/abitype/dist/esm/human-readable/errors/abiItem.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/abiItem.js var UnknownTypeError = class extends BaseError { constructor({ type }) { super("Unknown type.", { @@ -199,7 +199,7 @@ var UnknownSolidityTypeError = class extends BaseError { } }; -// ../../node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js var InvalidParameterError = class extends BaseError { constructor({ param }) { super("Invalid ABI parameter.", { @@ -277,7 +277,7 @@ var InvalidAbiTypeParameterError = class extends BaseError { } }; -// ../../node_modules/abitype/dist/esm/human-readable/errors/signature.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/signature.js var InvalidSignatureError = class extends BaseError { constructor({ signature, type }) { super(`Invalid ${type} signature.`, { @@ -319,7 +319,7 @@ var InvalidStructSignatureError = class extends BaseError { } }; -// ../../node_modules/abitype/dist/esm/human-readable/errors/struct.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/struct.js var CircularReferenceError = class extends BaseError { constructor({ type }) { super("Circular reference detected.", { @@ -334,7 +334,7 @@ var CircularReferenceError = class extends BaseError { } }; -// ../../node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js var InvalidParenthesisError = class extends BaseError { constructor({ current, depth }) { super("Unbalanced parentheses.", { @@ -352,7 +352,7 @@ var InvalidParenthesisError = class extends BaseError { } }; -// ../../node_modules/abitype/dist/esm/human-readable/runtime/cache.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/cache.js function getParameterCacheKey(param, type, structs) { let structKey = ""; if (structs) @@ -424,7 +424,7 @@ var parameterCache = /* @__PURE__ */ new Map([ ] ]); -// ../../node_modules/abitype/dist/esm/human-readable/runtime/utils.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/utils.js function parseSignature(signature, structs = {}) { if (isFunctionSignature(signature)) { const match = execFunctionSignature(signature); @@ -607,7 +607,7 @@ function isValidDataLocation(type, isArray) { return isArray || type === "bytes" || type === "string" || type === "tuple"; } -// ../../node_modules/abitype/dist/esm/human-readable/runtime/structs.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/structs.js function parseStructs(signatures) { const shallowStructs = {}; const signaturesLength = signatures.length; @@ -677,7 +677,7 @@ function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new return components; } -// ../../node_modules/abitype/dist/esm/human-readable/parseAbi.js +// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/parseAbi.js function parseAbi(signatures) { const structs = parseStructs(signatures); const abi = []; @@ -3698,7 +3698,7 @@ async function call(client, args) { return { data: response }; } catch (err) { const data2 = getRevertErrorData(err); - const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-IAE5UWYX.js"); + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-MMGH6DXX.js"); if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to) return { data: await offchainLookup2(client, { data: data2, to }) }; if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") @@ -4016,4 +4016,4 @@ export { @noble/hashes/esm/utils.js: (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */ -//# sourceMappingURL=chunk-KSHJJL6X.js.map \ No newline at end of file +//# sourceMappingURL=chunk-NTU6R7BC.js.map \ No newline at end of file diff --git a/dist/chunk-NTU6R7BC.js.map b/dist/chunk-NTU6R7BC.js.map new file mode 100644 index 0000000..07f42cc --- /dev/null +++ b/dist/chunk-NTU6R7BC.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/viem/node_modules/abitype/src/version.ts","../../../node_modules/viem/node_modules/abitype/src/errors.ts","../../../node_modules/viem/node_modules/abitype/src/regex.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiParameter.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiParameters.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiItem.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/signatures.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/abiItem.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/abiParameter.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/signature.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/struct.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/splitParameters.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/cache.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/utils.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/structs.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/parseAbi.ts","../../../node_modules/viem/accounts/utils/parseAccount.ts","../../../node_modules/viem/constants/abis.ts","../../../node_modules/viem/constants/contract.ts","../../../node_modules/viem/constants/contracts.ts","../../../node_modules/viem/errors/version.ts","../../../node_modules/viem/errors/base.ts","../../../node_modules/viem/errors/chain.ts","../../../node_modules/viem/constants/solidity.ts","../../../node_modules/viem/utils/abi/formatAbiItem.ts","../../../node_modules/viem/utils/data/isHex.ts","../../../node_modules/viem/utils/data/size.ts","../../../node_modules/viem/errors/abi.ts","../../../node_modules/viem/errors/data.ts","../../../node_modules/viem/utils/data/slice.ts","../../../node_modules/viem/utils/data/pad.ts","../../../node_modules/viem/errors/encoding.ts","../../../node_modules/viem/utils/data/trim.ts","../../../node_modules/viem/utils/encoding/fromHex.ts","../../../node_modules/viem/utils/encoding/toHex.ts","../../../node_modules/viem/utils/encoding/toBytes.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/viem/utils/hash/keccak256.ts","../../../node_modules/viem/utils/hash/hashSignature.ts","../../../node_modules/viem/utils/hash/normalizeSignature.ts","../../../node_modules/viem/utils/hash/toSignature.ts","../../../node_modules/viem/utils/hash/toSignatureHash.ts","../../../node_modules/viem/utils/hash/toFunctionSelector.ts","../../../node_modules/viem/errors/address.ts","../../../node_modules/viem/utils/lru.ts","../../../node_modules/viem/utils/address/isAddress.ts","../../../node_modules/viem/utils/address/getAddress.ts","../../../node_modules/viem/errors/cursor.ts","../../../node_modules/viem/utils/cursor.ts","../../../node_modules/viem/utils/encoding/fromBytes.ts","../../../node_modules/viem/utils/data/concat.ts","../../../node_modules/viem/utils/regex.ts","../../../node_modules/viem/utils/abi/encodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeErrorResult.ts","../../../node_modules/viem/utils/stringify.ts","../../../node_modules/viem/utils/hash/toEventSelector.ts","../../../node_modules/viem/utils/abi/getAbiItem.ts","../../../node_modules/viem/constants/unit.ts","../../../node_modules/viem/utils/unit/formatUnits.ts","../../../node_modules/viem/utils/unit/formatEther.ts","../../../node_modules/viem/utils/unit/formatGwei.ts","../../../node_modules/viem/errors/stateOverride.ts","../../../node_modules/viem/errors/transaction.ts","../../../node_modules/viem/errors/utils.ts","../../../node_modules/viem/errors/contract.ts","../../../node_modules/viem/utils/abi/decodeFunctionResult.ts","../../../node_modules/viem/utils/abi/encodeDeployData.ts","../../../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../../../node_modules/viem/utils/abi/encodeFunctionData.ts","../../../node_modules/viem/utils/chain/getChainContractAddress.ts","../../../node_modules/viem/errors/node.ts","../../../node_modules/viem/errors/request.ts","../../../node_modules/viem/utils/errors/getNodeError.ts","../../../node_modules/viem/utils/errors/getCallError.ts","../../../node_modules/viem/utils/formatters/extract.ts","../../../node_modules/viem/utils/formatters/transactionRequest.ts","../../../node_modules/viem/utils/promise/withResolvers.ts","../../../node_modules/viem/utils/promise/createBatchScheduler.ts","../../../node_modules/viem/utils/stateOverride.ts","../../../node_modules/viem/constants/number.ts","../../../node_modules/viem/utils/transaction/assertRequest.ts","../../../node_modules/viem/actions/public/call.ts","../../../node_modules/viem/errors/ccip.ts","../../../node_modules/viem/utils/address/isAddressEqual.ts","../../../node_modules/viem/utils/ccip.ts"],"sourcesContent":["export const version = '1.0.7'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n\n override name = 'AbiTypeError'\n\n constructor(shortMessage: string, args: BaseErrorArgs = {}) {\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 const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: abitype@${version}`,\n ].join('\\n')\n\n super(message)\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","// 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 type | 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 abiParameter - 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 abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter 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 [key in keyof components]: FormatAbiParameter<\n {\n type: components[key]['type']\n } & (IsNarrowable extends true\n ? { name: components[key]['name'] }\n : unknown) &\n (components[key] extends { components: readonly AbiParameter[] }\n ? { components: components[key]['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 : `${abiParameter['type']}${abiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${abiParameter['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 abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): 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 abiParameters - 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [key in keyof abiParameters]: 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: abiParameters): 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 {\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 abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem =\n Abi[number] extends abiItem\n ? string\n :\n | (abiItem extends AbiFunction\n ? AbiFunction extends abiItem\n ? string\n : `function ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${abiItem['stateMutability']}`\n : ''}${abiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters})`}`\n : never)\n | (abiItem extends AbiEvent\n ? AbiEvent extends abiItem\n ? string\n : `event ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiError\n ? AbiError extends abiItem\n ? string\n : `error ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiConstructor\n ? AbiConstructor extends abiItem\n ? string\n : `constructor(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiFallback\n ? AbiFallback extends abiItem\n ? string\n : `fallback() external${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiReceive\n ? AbiReceive extends abiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? abiParameters\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: abiItem,\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 if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n if (abiItem.type === 'fallback')\n return `fallback() external${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }` as Result\n return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n EventModifier,\n FunctionModifier,\n Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n errorSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isEventSignature(signature: string) {\n return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n eventSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n return execTyped<{\n name: string\n parameters: string\n stateMutability?: AbiStateMutability\n returns?: string\n }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?.*?)\\}$/\nexport function isStructSignature(signature: string) {\n return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n return execTyped<{ name: string; properties: string }>(\n structSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n /^constructor\\((?.*?)\\)(?:\\s(?payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex =\n /^fallback\\(\\) external(?:\\s(?payable{1}))?$/\nexport function isFallbackSignature(signature: string) {\n return fallbackSignatureRegex.test(signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set([\n 'memory',\n 'indexed',\n 'storage',\n 'calldata',\n])\nexport const eventModifiers = new Set(['indexed'])\nexport const functionModifiers = new Set([\n 'calldata',\n 'memory',\n 'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n override name = 'InvalidAbiItemError'\n\n constructor({ signature }: { signature: string | object }) {\n super('Failed to parse ABI item.', {\n details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n docsPath: '/api/human#parseabiitem-1',\n })\n }\n}\n\nexport class UnknownTypeError extends BaseError {\n override name = 'UnknownTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [\n `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n ],\n })\n }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n override name = 'UnknownSolidityTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n override name = 'InvalidAbiParameterError'\n\n constructor({ param }: { param: string | object }) {\n super('Failed to parse ABI parameter.', {\n details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n docsPath: '/api/human#parseabiparameter-1',\n })\n }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n override name = 'InvalidAbiParametersError'\n\n constructor({ params }: { params: string | object }) {\n super('Failed to parse ABI parameters.', {\n details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n docsPath: '/api/human#parseabiparameters-1',\n })\n }\n}\n\nexport class InvalidParameterError extends BaseError {\n override name = 'InvalidParameterError'\n\n constructor({ param }: { param: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n })\n }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n override name = 'SolidityProtectedKeywordError'\n\n constructor({ param, name }: { param: string; name: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n ],\n })\n }\n}\n\nexport class InvalidModifierError extends BaseError {\n override name = 'InvalidModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n ],\n })\n }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n override name = 'InvalidFunctionModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n ],\n })\n }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n override name = 'InvalidAbiTypeParameterError'\n\n constructor({\n abiParameter,\n }: {\n abiParameter: AbiParameter & { indexed?: boolean | undefined }\n }) {\n super('Invalid ABI parameter.', {\n details: JSON.stringify(abiParameter, null, 2),\n metaMessages: ['ABI parameter type is invalid.'],\n })\n }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n override name = 'InvalidSignatureError'\n\n constructor({\n signature,\n type,\n }: {\n signature: string\n type: AbiItemType | 'struct'\n }) {\n super(`Invalid ${type} signature.`, {\n details: signature,\n })\n }\n}\n\nexport class UnknownSignatureError extends BaseError {\n override name = 'UnknownSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Unknown signature.', {\n details: signature,\n })\n }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n override name = 'InvalidStructSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Invalid struct signature.', {\n details: signature,\n metaMessages: ['No properties exist.'],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n override name = 'CircularReferenceError'\n\n constructor({ type }: { type: string }) {\n super('Circular reference detected.', {\n metaMessages: [`Struct \"${type}\" is a circular reference.`],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n override name = 'InvalidParenthesisError'\n\n constructor({ current, depth }: { current: string; depth: number }) {\n super('Unbalanced parentheses.', {\n metaMessages: [\n `\"${current.trim()}\" has too many ${\n depth > 0 ? 'opening' : 'closing'\n } parentheses.`,\n ],\n details: `Depth \"${depth}\"`,\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport type { StructLookup } from '../types/structs.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n param: string,\n type?: AbiItemType | 'struct',\n structs?: StructLookup,\n) {\n let structKey = ''\n if (structs)\n for (const struct of Object.entries(structs)) {\n if (!struct) continue\n let propertyKey = ''\n for (const property of struct[1]) {\n propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`\n }\n structKey += `(${struct[0]}{${propertyKey}})`\n }\n if (type) return `${type}:${param}${structKey}`\n return param\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n string,\n AbiParameter & { indexed?: boolean }\n>([\n // Unnamed\n ['address', { type: 'address' }],\n ['bool', { type: 'bool' }],\n ['bytes', { type: 'bytes' }],\n ['bytes32', { type: 'bytes32' }],\n ['int', { type: 'int256' }],\n ['int256', { type: 'int256' }],\n ['string', { type: 'string' }],\n ['uint', { type: 'uint256' }],\n ['uint8', { type: 'uint8' }],\n ['uint16', { type: 'uint16' }],\n ['uint24', { type: 'uint24' }],\n ['uint32', { type: 'uint32' }],\n ['uint64', { type: 'uint64' }],\n ['uint96', { type: 'uint96' }],\n ['uint112', { type: 'uint112' }],\n ['uint160', { type: 'uint160' }],\n ['uint192', { type: 'uint192' }],\n ['uint256', { type: 'uint256' }],\n\n // Named\n ['address owner', { type: 'address', name: 'owner' }],\n ['address to', { type: 'address', name: 'to' }],\n ['bool approved', { type: 'bool', name: 'approved' }],\n ['bytes _data', { type: 'bytes', name: '_data' }],\n ['bytes data', { type: 'bytes', name: 'data' }],\n ['bytes signature', { type: 'bytes', name: 'signature' }],\n ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n ['bytes32 r', { type: 'bytes32', name: 'r' }],\n ['bytes32 root', { type: 'bytes32', name: 'root' }],\n ['bytes32 s', { type: 'bytes32', name: 's' }],\n ['string name', { type: 'string', name: 'name' }],\n ['string symbol', { type: 'string', name: 'symbol' }],\n ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint8 v', { type: 'uint8', name: 'v' }],\n ['uint256 balance', { type: 'uint256', name: 'balance' }],\n ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint256 value', { type: 'uint256', name: 'value' }],\n\n // Indexed\n [\n 'event:address indexed from',\n { type: 'address', name: 'from', indexed: true },\n ],\n ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n [\n 'event:uint indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n [\n 'event:uint256 indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n])\n","import type {\n AbiItemType,\n AbiType,\n SolidityArray,\n SolidityBytes,\n SolidityString,\n SolidityTuple,\n} from '../../abi.js'\nimport {\n bytesRegex,\n execTyped,\n integerRegex,\n isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n eventModifiers,\n execConstructorSignature,\n execErrorSignature,\n execEventSignature,\n execFunctionSignature,\n functionModifiers,\n isConstructorSignature,\n isErrorSignature,\n isEventSignature,\n isFallbackSignature,\n isFunctionSignature,\n isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n if (isFunctionSignature(signature)) {\n const match = execFunctionSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n const inputParams = splitParameters(match.parameters)\n const inputs = []\n const inputLength = inputParams.length\n for (let i = 0; i < inputLength; i++) {\n inputs.push(\n parseAbiParameter(inputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n\n const outputs = []\n if (match.returns) {\n const outputParams = splitParameters(match.returns)\n const outputLength = outputParams.length\n for (let i = 0; i < outputLength; i++) {\n outputs.push(\n parseAbiParameter(outputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n }\n\n return {\n name: match.name,\n type: 'function',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs,\n outputs,\n }\n }\n\n if (isEventSignature(signature)) {\n const match = execEventSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, {\n modifiers: eventModifiers,\n structs,\n type: 'event',\n }),\n )\n }\n return { name: match.name, type: 'event', inputs: abiParameters }\n }\n\n if (isErrorSignature(signature)) {\n const match = execErrorSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'error' }),\n )\n }\n return { name: match.name, type: 'error', inputs: abiParameters }\n }\n\n if (isConstructorSignature(signature)) {\n const match = execConstructorSignature(signature)\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n )\n }\n return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n }\n\n if (isFallbackSignature(signature)) return { type: 'fallback' }\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n /^\\((?.+?)\\)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n modifiers?: Set\n structs?: StructLookup\n type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n // optional namespace cache by `type`\n const parameterCacheKey = getParameterCacheKey(\n param,\n options?.type,\n options?.structs,\n )\n if (parameterCache.has(parameterCacheKey))\n return parameterCache.get(parameterCacheKey)!\n\n const isTuple = isTupleRegex.test(param)\n const match = execTyped<{\n array?: string\n modifier?: Modifier\n name?: string\n type: string\n }>(\n isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n param,\n )\n if (!match) throw new InvalidParameterError({ param })\n\n if (match.name && isSolidityKeyword(match.name))\n throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n const name = match.name ? { name: match.name } : {}\n const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n const structs = options?.structs ?? {}\n let type: string\n let components = {}\n if (isTuple) {\n type = 'tuple'\n const params = splitParameters(match.type)\n const components_ = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n // remove `modifiers` from `options` to prevent from being added to tuple components\n components_.push(parseAbiParameter(params[i]!, { structs }))\n }\n components = { components: components_ }\n } else if (match.type in structs) {\n type = 'tuple'\n components = { components: structs[match.type] }\n } else if (dynamicIntegerRegex.test(match.type)) {\n type = `${match.type}256`\n } else {\n type = match.type\n if (!(options?.type === 'struct') && !isSolidityType(type))\n throw new UnknownSolidityTypeError({ type })\n }\n\n if (match.modifier) {\n // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n if (!options?.modifiers?.has?.(match.modifier))\n throw new InvalidModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n\n // Check if resolved `type` is valid if there is a function modifier\n if (\n functionModifiers.has(match.modifier as FunctionModifier) &&\n !isValidDataLocation(type, !!match.array)\n )\n throw new InvalidFunctionModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n }\n\n const abiParameter = {\n type: `${type}${match.array ?? ''}`,\n ...name,\n ...indexed,\n ...components,\n }\n parameterCache.set(parameterCacheKey, abiParameter)\n return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n params: string,\n result: string[] = [],\n current = '',\n depth = 0,\n): readonly string[] {\n const length = params.trim().length\n // biome-ignore lint/correctness/noUnreachable: recursive\n for (let i = 0; i < length; i++) {\n const char = params[i]\n const tail = params.slice(i + 1)\n switch (char) {\n case ',':\n return depth === 0\n ? splitParameters(tail, [...result, current.trim()])\n : splitParameters(tail, result, `${current}${char}`, depth)\n case '(':\n return splitParameters(tail, result, `${current}${char}`, depth + 1)\n case ')':\n return splitParameters(tail, result, `${current}${char}`, depth - 1)\n default:\n return splitParameters(tail, result, `${current}${char}`, depth)\n }\n }\n\n if (current === '') return result\n if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n result.push(current.trim())\n return result\n}\n\nexport function isSolidityType(\n type: string,\n): type is Exclude {\n return (\n type === 'address' ||\n type === 'bool' ||\n type === 'function' ||\n type === 'string' ||\n bytesRegex.test(type) ||\n integerRegex.test(type)\n )\n}\n\nconst protectedKeywordsRegex =\n /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\n/** @internal */\nexport function isSolidityKeyword(name: string) {\n return (\n name === 'address' ||\n name === 'bool' ||\n name === 'function' ||\n name === 'string' ||\n name === 'tuple' ||\n bytesRegex.test(name) ||\n integerRegex.test(name) ||\n protectedKeywordsRegex.test(name)\n )\n}\n\n/** @internal */\nexport function isValidDataLocation(\n type: string,\n isArray: boolean,\n): type is Exclude<\n AbiType,\n SolidityString | Extract | SolidityArray\n> {\n return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n const shallowStructs: StructLookup = {}\n const signaturesLength = signatures.length\n for (let i = 0; i < signaturesLength; i++) {\n const signature = signatures[i]!\n if (!isStructSignature(signature)) continue\n\n const match = execStructSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n const properties = match.properties.split(';')\n\n const components: AbiParameter[] = []\n const propertiesLength = properties.length\n for (let k = 0; k < propertiesLength; k++) {\n const property = properties[k]!\n const trimmed = property.trim()\n if (!trimmed) continue\n const abiParameter = parseAbiParameter(trimmed, {\n type: 'struct',\n })\n components.push(abiParameter)\n }\n\n if (!components.length) throw new InvalidStructSignatureError({ signature })\n shallowStructs[match.name] = components\n }\n\n // Resolve nested structs inside each parameter\n const resolvedStructs: StructLookup = {}\n const entries = Object.entries(shallowStructs)\n const entriesLength = entries.length\n for (let i = 0; i < entriesLength; i++) {\n const [name, parameters] = entries[i]!\n resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n }\n\n return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n abiParameters: readonly (AbiParameter & { indexed?: true })[],\n structs: StructLookup,\n ancestors = new Set(),\n) {\n const components: AbiParameter[] = []\n const length = abiParameters.length\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i]!\n const isTuple = isTupleRegex.test(abiParameter.type)\n if (isTuple) components.push(abiParameter)\n else {\n const match = execTyped<{ array?: string; type: string }>(\n typeWithoutTupleRegex,\n abiParameter.type,\n )\n if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n const { array, type } = match\n if (type in structs) {\n if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n components.push({\n ...abiParameter,\n type: `tuple${array ?? ''}`,\n components: resolveStructs(\n structs[type] ?? [],\n structs,\n new Set([...ancestors, type]),\n ),\n })\n } else {\n if (isSolidityType(type)) components.push(abiParameter)\n else throw new UnknownTypeError({ type })\n }\n }\n }\n\n return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Error, Filter } from '../types.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * type Result = ParseAbi<\n * // ^? type Result = readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * [\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ]\n * >\n */\nexport type ParseAbi =\n string[] extends signatures\n ? Abi // If `T` was not able to be inferred (e.g. just `string[]`), return `Abi`\n : signatures extends readonly string[]\n ? signatures extends Signatures // Validate signatures\n ? ParseStructs extends infer sructs\n ? {\n [key in keyof signatures]: signatures[key] extends string\n ? ParseSignature\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends infer result\n ? result extends readonly []\n ? never\n : result\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n * // ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi(\n signatures: signatures['length'] extends 0\n ? Error<'At least one signature required'>\n : Signatures extends signatures\n ? signatures\n : Signatures,\n): ParseAbi {\n const structs = parseStructs(signatures as readonly string[])\n const abi = []\n const length = signatures.length as number\n for (let i = 0; i < length; i++) {\n const signature = (signatures as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n abi.push(parseSignature(signature, structs))\n }\n return abi as unknown as ParseAbi\n}\n","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(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\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 {\n inputs: [],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n components: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'errors',\n type: 'tuple[]',\n },\n ],\n name: 'HttpError',\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 {\n name: 'resolve',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n { name: 'gateways', type: 'string[]' },\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 {\n name: 'reverse',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'string[]', name: 'gateways' },\n ],\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\n/** @internal */\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 name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n] as const\n\n/** [ERC-20 Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) */\nexport const erc20Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/**\n * [bytes32-flavored ERC-20](https://docs.makerdao.com/smart-contract-modules/mkr-module#4.-gotchas-potential-source-of-user-error)\n * for tokens (ie. Maker) that use bytes32 instead of string.\n */\nexport const erc20Abi_bytes32 = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/** [ERC-721 Non-Fungible Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) */\nexport const erc721Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'ApprovalForAll',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n name: 'approved',\n type: 'bool',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'getApproved',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'isApprovedForAll',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'operator',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'ownerOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'id',\n type: 'uint256',\n },\n {\n name: 'data',\n type: 'bytes',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'setApprovalForAll',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'operator',\n type: 'address',\n },\n {\n name: 'approved',\n type: 'bool',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenURI',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'tokeId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n] as const\n\n/** [ERC-4626 Tokenized Vaults Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-4626) */\nexport const erc4626Abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Deposit',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n name: 'allowance',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'approve',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'asset',\n outputs: [\n {\n name: 'assetTokenAddress',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'convertToAssets',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'convertToShares',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'deposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxDeposit',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxMint',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxRedeem',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxWithdraw',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'mint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewDeposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewMint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewRedeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewWithdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'redeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalAssets',\n outputs: [\n {\n name: 'totalManagedAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transfer',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transferFrom',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'withdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","export const aggregate3Signature = '0x82ad56cb'\n","export const deploylessCallViaBytecodeBytecode =\n '0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe'\n\nexport const deploylessCallViaFactoryBytecode =\n '0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe'\n\nexport const universalSignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n","export const version = '2.21.58'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\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(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (\n err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined\n )\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 constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint | undefined\n chain: Chain\n contract: { name: string; blockCreated?: number | undefined }\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 name: 'ChainDoesNotSupportContract',\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\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 name: 'ChainMismatchError',\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\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 name: 'ChainNotFoundError',\n },\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n })\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n { name: 'InvalidChainIdError' },\n )\n }\n}\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: 'Arithmetic 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","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 | undefined } = {},\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 | undefined } = {},\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 { 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 | undefined } = {},\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 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 type { Abi, 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 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 name: 'AbiConstructorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\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 name: 'AbiConstructorParamsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\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 {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\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 name: 'AbiDecodingDataSizeTooSmallError',\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 constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n })\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingArrayLengthMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\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 { name: 'AbiEncodingBytesSizeMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingLengthMismatchError' },\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\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 name: 'AbiErrorInputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(\n errorName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiErrorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\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 name: 'AbiErrorSignatureNotFoundError',\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\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 name: 'AbiEventSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(\n eventName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiEventNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(\n functionName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiFunctionNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\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 name: 'AbiFunctionOutputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\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 name: 'AbiFunctionSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(\n x: { abiItem: Abi[number]; type: string },\n y: { abiItem: Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n })\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n })\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\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 name: 'DecodeLogDataMismatch',\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 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 { name: 'DecodeLogTopicsMismatch' },\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\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, name: 'InvalidAbiEncodingType' },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\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, name: 'InvalidAbiDecodingType' },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n })\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\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 { name: 'InvalidDefinitionTypeError' },\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\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 { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\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 { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\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()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\n )\n }\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 = value 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: value,\n start?: number | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined) {\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(\n value: Hex | ByteArray,\n start?: number | undefined,\n end?: number | undefined,\n) {\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 {\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' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: value,\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 { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\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 { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\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 name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\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 { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim(\n hexOrBytes: value,\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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to 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\n * - Example: https://viem.sh/docs/utilities/fromHex#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 to 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 | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 | undefined\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#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#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 | undefined\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#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 {\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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toHex#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 | undefined\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#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 | undefined\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#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 | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\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#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: bigint | number | undefined\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${(\n signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : 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 | undefined\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#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 { 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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toBytes#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 | undefined\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#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 | undefined\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#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#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(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\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#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","function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n// TODO: re-check https://issues.chromium.org/issues/42212588\n\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { abytes, aexists, anumber, aoutput } 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 isLE,\n byteSwap32,\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: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: 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 anumber(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 if (!isLE) byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE) byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input) {\n aexists(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 aexists(this, false);\n abytes(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 anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array) {\n aoutput(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 | (to extends 'bytes' ? ByteArray : never)\n | (to 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_?: to | undefined,\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 ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport function hashSignature(sig: string) {\n return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype 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 AbiEvent, 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 ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n const def_ = (() => {\n if (typeof def === 'string') return def\n return formatAbiItem(def)\n })()\n return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n | HashSignatureErrorType\n | ToSignatureErrorType\n | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n return hashSignature(toSignature(fn))\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToFunctionSelectorErrorType =\n | ToSignatureHashErrorType\n | SliceErrorType\n | ErrorType\n\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn: string | AbiFunction) =>\n slice(toSignatureHash(fn), 0, 4)\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\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 { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap
(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\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 const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n })\n }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n { name: 'PositionOutOfBoundsError' },\n )\n }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n RecursiveReadLimitExceededError & {\n name: 'RecursiveReadLimitExceededError'\n }\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n { name: 'RecursiveReadLimitExceededError' },\n )\n }\n}\n","import {\n NegativeOffsetError,\n type NegativeOffsetErrorType,\n PositionOutOfBoundsError,\n type PositionOutOfBoundsErrorType,\n RecursiveReadLimitExceededError,\n type RecursiveReadLimitExceededErrorType,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n bytes: ByteArray\n dataView: DataView\n position: number\n positionReadCount: Map\n recursiveReadCount: number\n recursiveReadLimit: number\n remaining: number\n assertReadLimit(position?: number): void\n assertPosition(position: number): void\n decrementPosition(offset: number): void\n getReadCount(position?: number): number\n incrementPosition(offset: number): void\n inspectByte(position?: number): ByteArray[number]\n inspectBytes(length: number, position?: number): ByteArray\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: ByteArray[number]): void\n pushBytes(bytes: ByteArray): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): ByteArray[number]\n readBytes(length: number, size?: number): ByteArray\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\n\ntype CursorErrorType =\n | CursorAssertPositionErrorType\n | CursorDecrementPositionErrorType\n | CursorIncrementPositionErrorType\n | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype StaticCursorErrorType =\n | NegativeOffsetErrorType\n | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n })\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n })\n },\n decrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position - offset\n this.assertPosition(position)\n this.position = position\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0\n },\n incrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position + offset\n this.assertPosition(position)\n this.position = position\n },\n inspectByte(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + length - 1)\n return this.bytes.subarray(position, position + length)\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 1)\n return this.dataView.getUint16(position)\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 2)\n return (\n (this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2)\n )\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 3)\n return this.dataView.getUint32(position)\n },\n pushByte(byte: ByteArray[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: ByteArray) {\n this.assertPosition(this.position + bytes.length - 1)\n this.bytes.set(bytes, this.position)\n this.position += bytes.length\n },\n pushUint8(value: number) {\n this.assertPosition(this.position)\n this.bytes[this.position] = value\n this.position++\n },\n pushUint16(value: number) {\n this.assertPosition(this.position + 1)\n this.dataView.setUint16(this.position, value)\n this.position += 2\n },\n pushUint24(value: number) {\n this.assertPosition(this.position + 2)\n this.dataView.setUint16(this.position, value >> 8)\n this.dataView.setUint8(this.position + 2, value & ~4294967040)\n this.position += 3\n },\n pushUint32(value: number) {\n this.assertPosition(this.position + 3)\n this.dataView.setUint32(this.position, value)\n this.position += 4\n },\n readByte() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectByte()\n this.position++\n return value\n },\n readBytes(length, size) {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectBytes(length)\n this.position += size ?? length\n return value\n },\n readUint8() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint8()\n this.position += 1\n return value\n },\n readUint16() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint16()\n this.position += 2\n return value\n },\n readUint24() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint24()\n this.position += 3\n return value\n },\n readUint32() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint32()\n this.position += 4\n return value\n },\n get remaining() {\n return this.bytes.length - this.position\n },\n setPosition(position) {\n const oldPosition = this.position\n this.assertPosition(position)\n this.position = position\n return () => (this.position = oldPosition)\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n const count = this.getReadCount()\n this.positionReadCount.set(this.position, count + 1)\n if (count > 0) this.recursiveReadCount++\n },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n | CursorErrorType\n | StaticCursorErrorType\n | ErrorType\n\nexport function createCursor(\n bytes: ByteArray,\n { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n type AssertSizeErrorType,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n assertSize,\n hexToBigInt,\n hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n | to\n | {\n /** Size of the bytes. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromBytesReturnType = to extends 'string'\n ? string\n : to extends 'hex'\n ? Hex\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromBytesErrorType =\n | BytesToHexErrorType\n | BytesToBigIntErrorType\n | BytesToBoolErrorType\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n bytes: ByteArray,\n toOrOpts: FromBytesParameters,\n): FromBytesReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number')\n return bytesToNumber(bytes, opts) as FromBytesReturnType\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts) as FromBytesReturnType\n if (to === 'boolean')\n return bytesToBool(bytes, opts) as FromBytesReturnType\n if (to === 'string')\n return bytesToString(bytes, opts) as FromBytesReturnType\n return bytesToHex(bytes, opts) as FromBytesReturnType\n}\n\nexport type BytesToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n | BytesToHexErrorType\n | HexToBigIntErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n bytes: ByteArray,\n opts: BytesToBigIntOpts = {},\n): bigint {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n bytes_: ByteArray,\n opts: BytesToBoolOpts = {},\n): boolean {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes)\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes)\n return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n | BytesToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n bytes: ByteArray,\n opts: BytesToNumberOpts = {},\n): number {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n bytes_: ByteArray,\n opts: BytesToStringOpts = {},\n): string {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat(\n values: readonly value[],\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","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\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","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 { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.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'\nimport { integerRegex } from '../regex.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 *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: params,\n values: params 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 as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values: values as any,\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\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams({\n params,\n values,\n}: {\n params: params\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\ntype PrepareParamErrorType =\n | EncodeAddressErrorType\n | EncodeArrayErrorType\n | EncodeBytesErrorType\n | EncodeBoolErrorType\n | EncodeNumberErrorType\n | EncodeStringErrorType\n | EncodeTupleErrorType\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam({\n param,\n value,\n}: {\n param: param\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 const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\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\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | 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\ntype 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\ntype EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray(\n value: AbiParameterToPrimitiveType,\n {\n length,\n param,\n }: {\n length: number | null\n param: param\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\ntype EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes(\n value: Hex,\n { param }: { param: param },\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 !== Number.parseInt(paramSize))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n if (typeof value !== 'boolean')\n throw new BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\ntype 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\ntype EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType,\n { param }: { param: param },\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\ntype 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 { AbiParameter, AbiParametersToPrimitiveTypes } from 'abitype'\n\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type BytesToBigIntErrorType,\n type BytesToBoolErrorType,\n type BytesToNumberErrorType,\n type BytesToStringErrorType,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n params extends readonly AbiParameter[] ? params : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | DecodeParameterErrorType\n | SizeErrorType\n | CreateCursorErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const params extends readonly AbiParameter[],\n>(\n params: params,\n data: ByteArray | Hex,\n): DecodeAbiParametersReturnType {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data\n const cursor = createCursor(bytes)\n\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n\n let consumed = 0\n const values = []\n for (let i = 0; i < params.length; ++i) {\n const param = params[i]\n cursor.setPosition(consumed)\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n })\n consumed += consumed_\n values.push(data)\n }\n return values as DecodeAbiParametersReturnType\n}\n\ntype DecodeParameterErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeStringErrorType\n | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n if (param.type === 'address') return decodeAddress(cursor)\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | BytesToHexErrorType\n | SliceBytesErrorType\n | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n const value = cursor.readBytes(32)\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n cursor: Cursor,\n param: AbiParameter,\n { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 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 // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n | BytesToNumberErrorType\n | BytesToHexErrorType\n | ErrorType\n\nfunction decodeBytes(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [bytesToHex(data), 32]\n }\n\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size), 32))\n return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n | BytesToNumberErrorType\n | BytesToBigIntErrorType\n | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256')\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n cursor: Cursor,\n param: TupleAbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\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 // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\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 [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(\n cursor: Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = bytesToString(trim(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\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 } 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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n ContractErrorArgs,\n ContractErrorName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { slice } from '../data/slice.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = { abi?: abi | undefined; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allErrorNames extends ContractErrorName = ContractErrorName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [errorName in allErrorNames]: {\n abiItem: abi extends Abi\n ? Abi extends abi\n ? AbiItem\n : ExtractAbiError\n : AbiItem\n args: ContractErrorArgs\n errorName: errorName\n }\n }[allErrorNames]\n >\n : {\n abiItem: AbiItem\n args: readonly unknown[] | undefined\n errorName: string\n }\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult(\n parameters: DecodeErrorResultParameters,\n): DecodeErrorResultReturnType {\n const { abi, data } = parameters as DecodeErrorResultParameters\n\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...(abi || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args:\n 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType\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 type { ErrorType } from '../../errors/utils.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport {\n AbiItemAmbiguityError,\n type AbiItemAmbiguityErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ExtractAbiItemForArgs,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nexport type GetAbiItemParameters<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n ///\n allArgs = AbiItemArgs,\n allNames = AbiItemName,\n> = {\n abi: abi\n name:\n | allNames // show all options\n | (name extends allNames ? name : never) // infer value\n | Hex // function selector\n} & UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | ToFunctionSelectorErrorType\n | AbiItemAmbiguityErrorType\n | ErrorType\n\nexport type GetAbiItemReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n> = abi extends Abi\n ? Abi extends abi\n ? AbiItem | undefined\n : ExtractAbiItemForArgs<\n abi,\n name,\n args extends AbiItemArgs ? args : AbiItemArgs\n >\n : AbiItem | undefined\n\nexport function getAbiItem<\n const abi extends Abi | readonly unknown[],\n name extends AbiItemName,\n const args extends AbiItemArgs | undefined = undefined,\n>(\n parameters: GetAbiItemParameters,\n): GetAbiItemReturnType {\n const { abi, args = [], name } = parameters as unknown as GetAbiItemParameters\n\n const isSelector = isHex(name, { strict: false })\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return toEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0)\n return undefined as GetAbiItemReturnType\n if (abiItems.length === 1)\n return abiItems[0] as GetAbiItemReturnType\n\n let matchedAbiItem: AbiItem | undefined = undefined\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)\n return abiItem as GetAbiItemReturnType\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.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, abiParameter)\n })\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (\n matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs\n ) {\n const ambiguousTypes = getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AbiItemAmbiguityError(\n {\n abiItem,\n type: ambiguousTypes[0],\n },\n {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1],\n },\n )\n }\n\n matchedAbiItem = abiItem\n }\n }\n\n if (matchedAbiItem)\n return matchedAbiItem as GetAbiItemReturnType\n return abiItems[0] as GetAbiItemReturnType\n}\n\ntype IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\n/** @internal */\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, { strict: false })\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\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameter[],\n targetParameters: readonly AbiParameter[],\n args: AbiItemArgs,\n): AbiParameter['type'][] | undefined {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex]\n const targetParameter = targetParameters[parameterIndex]\n\n if (\n sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter\n )\n return getAmbiguousTypes(\n sourceParameter.components,\n targetParameter.components,\n (args as any)[parameterIndex],\n )\n\n const types = [sourceParameter.type, targetParameter.type]\n\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20')) return true\n if (types.includes('address') && types.includes('string'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\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 { 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\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","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\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\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 { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { BaseError } from './base.js'\n\nexport type AccountStateConflictErrorType = AccountStateConflictError & {\n name: 'AccountStateConflictError'\n}\n\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n })\n }\n}\n\nexport type StateAssignmentConflictErrorType = StateAssignmentConflictError & {\n name: 'StateAssignmentConflictError'\n}\n\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n })\n }\n}\n\n/** @internal */\nexport function prettyStateMapping(stateMapping: StateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`\n }, '')\n}\n\nexport function prettyStateOverride(stateOverride: StateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`\n if (state.nonce) val += ` nonce: ${state.nonce}\\n`\n if (state.balance) val += ` balance: ${state.balance}\\n`\n if (state.code) val += ` code: ${state.code}\\n`\n if (state.state) {\n val += ' state:\\n'\n val += prettyStateMapping(state.state)\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n'\n val += prettyStateMapping(state.stateDiff)\n }\n return val\n }, ' State Override:\\n')\n .slice(0, -1)\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 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 { name: 'FeeConflictError' },\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n })\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\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 '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n })\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\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 name: 'InvalidSerializedTransactionError',\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 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 { name: 'InvalidStorageKeySizeError' },\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'TransactionExecutionError',\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n blockTag?: BlockTag | undefined\n hash?: Hash | undefined\n index?: number | undefined\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 name: 'TransactionNotFoundError',\n })\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\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 name: 'TransactionReceiptNotFoundError',\n },\n )\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n { name: 'WaitForTransactionReceiptTimeoutError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nexport type ErrorType = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\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 { prettyStateOverride } from './stateOverride.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 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 stateOverride,\n }: CallParameters & {\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n let 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 if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`\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 name: 'CallExecutionError',\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[] | undefined\n override cause: BaseError\n contractAddress?: Address | undefined\n formattedArgs?: string | undefined\n functionName: string\n sender?: Address | undefined\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 | undefined\n contractAddress?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\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 prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'ContractFunctionExecutionError',\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 data?: DecodeErrorResultReturnType | undefined\n reason?: string | undefined\n signature?: Hex | undefined\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: {\n abi: Abi\n data?: Hex | undefined\n functionName: string\n message?: string | undefined\n }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined = undefined\n let metaMessages: string[] | undefined\n let reason: string | undefined\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 name: 'ContractFunctionRevertedError',\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 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 name: 'ContractFunctionZeroDataError',\n })\n }\n}\n\nexport type CounterfactualDeploymentFailedErrorType =\n CounterfactualDeploymentFailedError & {\n name: 'CounterfactualDeploymentFailedError'\n }\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }: { factory?: Address | undefined }) {\n super(\n `Deployment for counterfactual contract call failed${\n factory ? ` for factory \"${factory}\".` : ''\n }`,\n {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n },\n )\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n\n data?: Hex | { data?: Hex | undefined } | undefined\n\n constructor({\n data,\n message,\n }: {\n data?: Hex | { data?: Hex | undefined } | undefined\n message?: string | undefined\n }) {\n super(message || '', { name: 'RawContractError' })\n this.data = data\n }\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n data: Hex\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | undefined }\n : { functionName: functionName | allFunctionNames }\n : { functionName?: functionName | allFunctionNames | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type DecodeFunctionResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n> = ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n args\n>\n\nexport type DecodeFunctionResultErrorType =\n | AbiFunctionNotFoundErrorType\n | AbiFunctionOutputsNotFoundErrorType\n | DecodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function decodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n const args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n>(\n parameters: DecodeFunctionResultParameters,\n): DecodeFunctionResultReturnType {\n const { abi, args, functionName, data } =\n parameters as DecodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, args, name: functionName })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\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)\n return values as DecodeFunctionResultReturnType\n if (values && values.length === 1)\n return values[0] as DecodeFunctionResultReturnType\n return undefined as DecodeFunctionResultReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n hasConstructor = abi extends Abi\n ? Abi extends abi\n ? true\n : [Extract] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractConstructorArgs,\n> = {\n abi: abi\n bytecode: Hex\n} & UnionEvaluate<\n hasConstructor extends false\n ? { args?: undefined }\n : readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n>\n\nexport type EncodeDeployDataReturnType = Hex\n\nexport type EncodeDeployDataErrorType =\n | AbiConstructorNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | ErrorType\n\nexport function encodeDeployData(\n parameters: EncodeDeployDataParameters,\n): EncodeDeployDataReturnType {\n const { abi, args, bytecode } = parameters as EncodeDeployDataParameters\n if (!args || args.length === 0) return bytecode\n\n const description = abi.find((x) => 'type' in x && x.type === 'constructor')\n if (!description) throw new AbiConstructorNotFoundError({ docsPath })\n if (!('inputs' in description))\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n if (!description.inputs || description.inputs.length === 0)\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n\n const data = encodeAbiParameters(description.inputs, args)\n return concatHex([bytecode, data!])\n}\n","import type {\n Abi,\n AbiStateMutability,\n ExtractAbiFunction,\n ExtractAbiFunctions,\n} from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionData'\n\nexport type PrepareEncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<{ args?: allArgs | undefined }> &\n (hasFunctions extends true ? unknown : never)\n\nexport type PrepareEncodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n> = {\n abi: abi extends Abi\n ? functionName extends ContractFunctionName\n ? [ExtractAbiFunction]\n : abi\n : Abi\n functionName: Hex\n}\n\nexport type PrepareEncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function prepareEncodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: PrepareEncodeFunctionDataParameters,\n): PrepareEncodeFunctionDataReturnType {\n const { abi, args, functionName } =\n parameters as PrepareEncodeFunctionDataParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n } as unknown as PrepareEncodeFunctionDataReturnType\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport type { AbiFunctionNotFoundErrorType } from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport type { FormatAbiItemErrorType } from './formatAbiItem.js'\nimport type { GetAbiItemErrorType } from './getAbiItem.js'\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js'\n\nexport type EncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | Hex\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionDataReturnType = Hex\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionDataParameters,\n): EncodeFunctionDataReturnType {\n const { args } = parameters as EncodeFunctionDataParameters\n\n const { abi, functionName } = (() => {\n if (\n parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x')\n )\n return parameters as { abi: Abi; functionName: Hex }\n return prepareEncodeFunctionData(parameters)\n })()\n\n const abiItem = abi[0]\n const signature = functionName\n\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\n : undefined\n return concatHex([signature, data ?? '0x'])\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 | undefined\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 { 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 constructor({\n cause,\n message,\n }: { cause?: BaseError | undefined; message?: string | undefined } = {}) {\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 name: 'ExecutionRevertedError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooHighError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooLowError',\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause, name: 'NonceTooHighError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\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, name: 'NonceTooLowError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause, name: 'NonceMaxValueError' },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage =\n /insufficient funds|exceeds transaction sender account balance/\n constructor({ cause }: { cause?: BaseError | undefined } = {}) {\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 name: 'InsufficientFundsError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\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 name: 'IntrinsicGasTooHighError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n name: 'IntrinsicGasTooLowError',\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 constructor({ cause }: { cause?: BaseError | undefined }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\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 constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\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 name: 'TipAboveFeeCapError',\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }: { cause?: BaseError | undefined }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\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 body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\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 constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; data?: unknown; 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 name: 'RpcRequestError',\n })\n this.code = error.code\n this.data = error.data\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\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 name: 'TimeoutError',\n })\n }\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'\nimport type { ExactPartial } from '../../types/utils.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 = ExactPartial<\n SendTransactionParameters\n>\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 =\n err instanceof BaseError\n ? err.walk(\n (e) =>\n (e as { code: number } | null | undefined)?.code ===\n ExecutionRevertedError.code,\n )\n : err\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\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 { 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 | undefined\n docsPath?: string | undefined\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","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'] | undefined },\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 { AuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { bytesToHex, numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n chain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n request: ExactPartial,\n) {\n const rpcRequest = {} as RpcTransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(\n request.authorizationList,\n )\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = (request.blobs as ByteArray[]).map((x) =>\n bytesToHex(x),\n )\n else rpcRequest.blobs = request.blobs\n }\n if (typeof request.data !== 'undefined') rpcRequest.data = request.data\n if (typeof request.from !== 'undefined') rpcRequest.from = request.from\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce)\n if (typeof request.to !== 'undefined') rpcRequest.to = request.to\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type]\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value)\n\n return rpcRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: AuthorizationList,\n): RpcAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n address: authorization.contractAddress,\n r: authorization.r,\n s: authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }) as any,\n ) as RpcAuthorizationList\n}\n","/** @internal */\nexport type PromiseWithResolvers = {\n promise: Promise\n resolve: (value: type | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\n/** @internal */\nexport function withResolvers(): PromiseWithResolvers {\n let resolve: PromiseWithResolvers['resolve'] = () => undefined\n let reject: PromiseWithResolvers['reject'] = () => undefined\n\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_\n reject = reject_\n })\n\n return { promise, resolve, reject }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type PromiseWithResolvers, withResolvers } from './withResolvers.js'\n\ntype Resolved = [\n result: returnType[number],\n results: returnType,\n]\n\ntype SchedulerItem = {\n args: unknown\n resolve: PromiseWithResolvers['resolve']\n reject: PromiseWithResolvers['reject']\n}\n\ntype BatchResultsCompareFn = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise>\n : (args: parameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\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 parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i]\n resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i]\n reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\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: parameters) {\n const { promise, resolve, reject } = withResolvers()\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, resolve, reject })\n return promise\n }\n\n setScheduler({ args, resolve, reject })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n InvalidBytesLengthError,\n type InvalidBytesLengthErrorType,\n} from '../errors/data.js'\nimport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from '../errors/stateOverride.js'\nimport type {\n RpcAccountStateOverride,\n RpcStateMapping,\n RpcStateOverride,\n} from '../types/rpc.js'\nimport type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { isAddress } from './address/isAddress.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\n\ntype SerializeStateMappingParameters = StateMapping | undefined\n\ntype SerializeStateMappingErrorType = InvalidBytesLengthErrorType\n\n/** @internal */\nexport function serializeStateMapping(\n stateMapping: SerializeStateMappingParameters,\n): RpcStateMapping | undefined {\n if (!stateMapping || stateMapping.length === 0) return undefined\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n })\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n })\n acc[slot] = value\n return acc\n }, {} as RpcStateMapping)\n}\n\ntype SerializeAccountStateOverrideParameters = Omit<\n StateOverride[number],\n 'address'\n>\n\ntype SerializeAccountStateOverrideErrorType =\n | NumberToHexErrorType\n | StateAssignmentConflictErrorType\n | SerializeStateMappingErrorType\n\n/** @internal */\nexport function serializeAccountStateOverride(\n parameters: SerializeAccountStateOverrideParameters,\n): RpcAccountStateOverride {\n const { balance, nonce, state, stateDiff, code } = parameters\n const rpcAccountStateOverride: RpcAccountStateOverride = {}\n if (code !== undefined) rpcAccountStateOverride.code = code\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance)\n if (nonce !== undefined) rpcAccountStateOverride.nonce = numberToHex(nonce)\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state)\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state) throw new StateAssignmentConflictError()\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff)\n }\n return rpcAccountStateOverride\n}\n\ntype SerializeStateOverrideParameters = StateOverride | undefined\n\nexport type SerializeStateOverrideErrorType =\n | InvalidAddressErrorType\n | AccountStateConflictErrorType\n | SerializeAccountStateOverrideErrorType\n\n/** @internal */\nexport function serializeStateOverride(\n parameters?: SerializeStateOverrideParameters,\n): RpcStateOverride | undefined {\n if (!parameters) return undefined\n const rpcStateOverride: RpcStateOverride = {}\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address })\n rpcStateOverride[address] = serializeAccountStateOverride(accountState)\n }\n return rpcStateOverride\n}\n","export const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { maxUint256 } from '../../constants/number.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 type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = ExactPartial<\n SendTransactionParameters\n>\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 > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import { type Address, parseAbi } 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 {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n} from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ChainDoesNotSupportContract,\n ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n CounterfactualDeploymentFailedError,\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 { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.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 {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type CallParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Whether or not to enable multicall batching on this call. */\n batch?: boolean | undefined\n /** Bytecode to perform the call on. */\n code?: Hex | undefined\n /** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). */\n factory?: Address | undefined\n /** Calldata to execute on the factory to deploy the contract. */\n factoryData?: Hex | undefined\n /** State overrides for the call. */\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedCall =\n FormattedTransactionRequest\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | ScheduleMulticallErrorType\n | RequestErrorType\n | ToDeploylessCallViaBytecodeDataErrorType\n | ToDeploylessCallViaFactoryDataErrorType\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\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 blobs,\n code,\n data: data_,\n factory,\n factoryData,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n stateOverride,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n if (code && (factory || factoryData))\n throw new BaseError(\n 'Cannot provide both `code` & `factory`/`factoryData` as parameters.',\n )\n if (code && to)\n throw new BaseError('Cannot provide both `code` & `to` as parameters.')\n\n // Check if the call is deployless via bytecode.\n const deploylessCallViaBytecode = code && data_\n // Check if the call is deployless via a factory.\n const deploylessCallViaFactory = factory && factoryData && to && data_\n const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory\n\n const data = (() => {\n if (deploylessCallViaBytecode)\n return toDeploylessCallViaBytecodeData({\n code,\n data: data_,\n })\n if (deploylessCallViaFactory)\n return toDeploylessCallViaFactoryData({\n data: data_,\n factory,\n factoryData,\n to,\n })\n return data_\n })()\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\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 blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to: deploylessCall ? undefined : to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) {\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: rpcStateOverride\n ? [\n request as ExactPartial,\n block,\n rpcStateOverride,\n ]\n : [request as ExactPartial, block],\n })\n if (response === '0x') return { data: undefined }\n return { data: response }\n } catch (err) {\n const data = getRevertErrorData(err)\n\n // Check for CCIP-Read offchain lookup signature.\n const { offchainLookup, offchainLookupSignature } = await import(\n '../../utils/ccip.js'\n )\n if (\n client.ccipRead !== false &&\n data?.slice(0, 10) === offchainLookupSignature &&\n to\n )\n return { data: await offchainLookup(client, { data, to }) }\n\n // Check for counterfactual deployment error.\n if (deploylessCall && data?.slice(0, 10) === '0x101bb98d')\n throw new CounterfactualDeploymentFailedError({ factory })\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 | undefined\n to: Address\n}\n\ntype 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\ntype ToDeploylessCallViaBytecodeDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaBytecodeData(parameters: {\n code: Hex\n data: Hex\n}) {\n const { code, data } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(bytes, bytes)']),\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [code, data],\n })\n}\n\ntype ToDeploylessCallViaFactoryDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaFactoryData(parameters: {\n data: Hex\n factory: Address\n factoryData: Hex\n to: Address\n}) {\n const { data, factory, factoryData, to } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(address, bytes, address, bytes)']),\n bytecode: deploylessCallViaFactoryBytecode,\n args: [to, data, factory, factoryData],\n })\n}\n\n/** @internal */\nexport type GetRevertErrorDataErrorType = ErrorType\n\n/** @internal */\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 { Address } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type OffchainLookupErrorType = OffchainLookupError & {\n name: 'OffchainLookupError'\n}\nexport class OffchainLookupError extends BaseError {\n constructor({\n callbackSelector,\n cause,\n data,\n extraData,\n sender,\n urls,\n }: {\n callbackSelector: Hex\n cause: BaseError\n data: Hex\n extraData: Hex\n sender: Address\n urls: readonly string[]\n }) {\n super(\n cause.shortMessage ||\n 'An error occurred while fetching for an offchain result.',\n {\n cause,\n metaMessages: [\n ...(cause.metaMessages || []),\n cause.metaMessages?.length ? '' : [],\n 'Offchain Gateway Call:',\n urls && [\n ' Gateway URL(s):',\n ...urls.map((url) => ` ${getUrl(url)}`),\n ],\n ` Sender: ${sender}`,\n ` Data: ${data}`,\n ` Callback selector: ${callbackSelector}`,\n ` Extra data: ${extraData}`,\n ].flat(),\n name: 'OffchainLookupError',\n },\n )\n }\n}\n\nexport type OffchainLookupResponseMalformedErrorType =\n OffchainLookupResponseMalformedError & {\n name: 'OffchainLookupResponseMalformedError'\n }\nexport class OffchainLookupResponseMalformedError extends BaseError {\n constructor({ result, url }: { result: any; url: string }) {\n super(\n 'Offchain gateway response is malformed. Response data must be a hex value.',\n {\n metaMessages: [\n `Gateway URL: ${getUrl(url)}`,\n `Response: ${stringify(result)}`,\n ],\n name: 'OffchainLookupResponseMalformedError',\n },\n )\n }\n}\n\n/** @internal */\nexport type OffchainLookupSenderMismatchErrorType =\n OffchainLookupSenderMismatchError & {\n name: 'OffchainLookupSenderMismatchError'\n }\nexport class OffchainLookupSenderMismatchError extends BaseError {\n constructor({ sender, to }: { sender: Address; to: Address }) {\n super(\n 'Reverted sender address does not match target contract address (`to`).',\n {\n metaMessages: [\n `Contract address: ${to}`,\n `OffchainLookup sender address: ${sender}`,\n ],\n name: 'OffchainLookupSenderMismatchError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { isAddress } from './isAddress.js'\n\nexport type IsAddressEqualReturnType = boolean\nexport type IsAddressEqualErrorType = InvalidAddressErrorType | ErrorType\n\nexport function isAddressEqual(a: Address, b: Address) {\n if (!isAddress(a, { strict: false }))\n throw new InvalidAddressError({ address: a })\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b })\n return a.toLowerCase() === b.toLowerCase()\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { BaseError } from '../errors/base.js'\nimport {\n OffchainLookupError,\n type OffchainLookupErrorType as OffchainLookupErrorType_,\n OffchainLookupResponseMalformedError,\n type OffchainLookupResponseMalformedErrorType,\n OffchainLookupSenderMismatchError,\n} from '../errors/ccip.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n} from '../errors/request.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\n\nimport type { Client } from '../clients/createClient.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport { decodeErrorResult } from './abi/decodeErrorResult.js'\nimport { encodeAbiParameters } from './abi/encodeAbiParameters.js'\nimport { isAddressEqual } from './address/isAddressEqual.js'\nimport { concat } from './data/concat.js'\nimport { isHex } from './data/isHex.js'\nimport { stringify } from './stringify.js'\n\nexport const offchainLookupSignature = '0x556f1830'\nexport const offchainLookupAbiItem = {\n name: 'OffchainLookup',\n type: 'error',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'urls',\n type: 'string[]',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n {\n name: 'callbackFunction',\n type: 'bytes4',\n },\n {\n name: 'extraData',\n type: 'bytes',\n },\n ],\n} as const satisfies Abi[number]\n\nexport type OffchainLookupErrorType = OffchainLookupErrorType_ | ErrorType\n\nexport async function offchainLookup(\n client: Client,\n {\n blockNumber,\n blockTag,\n data,\n to,\n }: Pick & {\n data: Hex\n to: Address\n },\n): Promise {\n const { args } = decodeErrorResult({\n data,\n abi: [offchainLookupAbiItem],\n })\n const [sender, urls, callData, callbackSelector, extraData] = args\n\n const { ccipRead } = client\n const ccipRequest_ =\n ccipRead && typeof ccipRead?.request === 'function'\n ? ccipRead.request\n : ccipRequest\n\n try {\n if (!isAddressEqual(to, sender))\n throw new OffchainLookupSenderMismatchError({ sender, to })\n\n const result = await ccipRequest_({ data: callData, sender, urls })\n\n const { data: data_ } = await call(client, {\n blockNumber,\n blockTag,\n data: concat([\n callbackSelector,\n encodeAbiParameters(\n [{ type: 'bytes' }, { type: 'bytes' }],\n [result, extraData],\n ),\n ]),\n to,\n } as CallParameters)\n\n return data_!\n } catch (err) {\n throw new OffchainLookupError({\n callbackSelector,\n cause: err as BaseError,\n data,\n extraData,\n sender,\n urls,\n })\n }\n}\n\nexport type CcipRequestParameters = {\n data: Hex\n sender: Address\n urls: readonly string[]\n}\n\nexport type CcipRequestReturnType = Hex\n\nexport type CcipRequestErrorType =\n | HttpRequestErrorType\n | OffchainLookupResponseMalformedErrorType\n | ErrorType\n\nexport async function ccipRequest({\n data,\n sender,\n urls,\n}: CcipRequestParameters): Promise {\n let error = new Error('An unknown error occurred.')\n\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i]\n const method = url.includes('{data}') ? 'GET' : 'POST'\n const body = method === 'POST' ? { data, sender } : undefined\n const headers: HeadersInit =\n method === 'POST' ? { 'Content-Type': 'application/json' } : {}\n\n try {\n const response = await fetch(\n url.replace('{sender}', sender).replace('{data}', data),\n {\n body: JSON.stringify(body),\n headers,\n method,\n },\n )\n\n let result: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n ) {\n result = (await response.json()).data\n } else {\n result = (await response.text()) as any\n }\n\n if (!response.ok) {\n error = new HttpRequestError({\n body,\n details: result?.error\n ? stringify(result.error)\n : response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n continue\n }\n\n if (!isHex(result)) {\n error = new OffchainLookupResponseMalformedError({\n result,\n url,\n })\n continue\n }\n\n return result\n } catch (err) {\n error = new HttpRequestError({\n body,\n details: (err as Error).message,\n url,\n })\n }\n }\n\n throw error\n}\n"],"mappings":";AAAO,IAAM,UAAU;;;ACUjB,IAAO,YAAP,MAAO,mBAAkB,MAAK;EAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,UAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,UAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,UAAM,UAAU;MACd,gBAAgB;MAChB;MACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;MACrD,GAAIA,YAAW,CAA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BAAkB,GACnE;AACA,kBAAU,MAAM,SAAS,KAAI,GAAI;MACnC,OAAO;AACL,iBAAU,MAAM,SAAS,KAAI;MAC/B;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,gBAAQ,IAAI,iBAAiB;UAC3B;UACA,SAAS,QAAQ,QACb,UAAU,OAAO,KAAK,IACtB,SAAS;UACb,SAAS,SAAS;UAClB,QAAQ,SAAS;UACjB;SACD;AACD;MACF;AAEA,UAAI,CAAC,MAAM,MAAM,GAAG;AAClB,gBAAQ,IAAI,qCAAqC;UAC/C;UACA;SACD;AACD;MACF;AAEA,aAAO;IACT,SAAS,KAAK;AACZ,cAAQ,IAAI,iBAAiB;QAC3B;QACA,SAAU,IAAc;QACxB;OACD;IACH;EACF;AAEA,QAAM;AACR;","names":["docsPath","version","docsPath","version","BaseError","docsPath","version","BaseError","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","BaseError","docsPath","BaseError","docsPath","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","size","BaseError","size","BaseError","size","size","size","encoder","BaseError","toBytes","toBytes","toBytes","toBytes","BaseError","BaseError","size","hash","BaseError","size","bytesRegex","integerRegex","size","integerRegex","length","BaseError","data","length","consumed","value","size","formatAbiItem","value","BaseError","BaseError","BaseError","BaseError","docsPath","BaseError","docsPath","docsPath","formatAbiItem","BaseError","BaseError","BaseError","docsPath","cause","formatted","args","split","BaseError","data","offchainLookup","offchainLookupSignature","args","size","BaseError"]} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index 0a5eb2b..cdb3835 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -19,11 +19,31 @@ declare class DeriveKeyProvider { private raProvider; constructor(teeMode?: string); private generateDeriveKeyAttestation; + /** + * Derives a raw key from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @returns The derived key. + */ rawDeriveKey(path: string, subject: string): Promise; + /** + * Derives an Ed25519 keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. + * @returns An object containing the derived keypair and attestation. + */ deriveEd25519Keypair(path: string, subject: string, agentId: string): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote; }>; + /** + * Derives an ECDSA keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. + * @returns An object containing the derived keypair and attestation. + */ deriveEcdsaKeypair(path: string, subject: string, agentId: string): Promise<{ keypair: PrivateKeyAccount; attestation: RemoteAttestationQuote; diff --git a/dist/index.js b/dist/index.js index 99b5fc2..39dafe0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -41,7 +41,7 @@ import { toHex, trim, wrapConstructor -} from "./chunk-KSHJJL6X.js"; +} from "./chunk-NTU6R7BC.js"; import "./chunk-PR4QN5HX.js"; // src/providers/remoteAttestationProvider.ts @@ -116,13 +116,22 @@ rtmr3: ${rtmrs[3]}f` } }; var remoteAttestationProvider = { - get: async (runtime, _message, _state) => { + get: async (runtime, message, _state) => { const teeMode = runtime.getSetting("TEE_MODE"); const provider = new RemoteAttestationProvider(teeMode); const agentId = runtime.agentId; try { - elizaLogger.log("Generating attestation for: ", agentId); - const attestation = await provider.generateAttestation(agentId, "raw"); + const attestationMessage = { + agentId, + timestamp: Date.now(), + message: { + userId: message.userId, + roomId: message.roomId, + content: message.content.text + } + }; + elizaLogger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; } catch (error) { console.error("Error in remote attestation provider:", error); @@ -1379,10 +1388,11 @@ var DeriveKeyProvider = class { this.client = endpoint ? new TappdClient2(endpoint) : new TappdClient2(); this.raProvider = new RemoteAttestationProvider(teeMode); } - async generateDeriveKeyAttestation(agentId, publicKey) { + async generateDeriveKeyAttestation(agentId, publicKey, subject) { const deriveKeyData = { agentId, - publicKey + publicKey, + subject }; const reportdata = JSON.stringify(deriveKeyData); elizaLogger2.log( @@ -1392,6 +1402,12 @@ var DeriveKeyProvider = class { elizaLogger2.log("Remote Attestation Quote generated successfully!"); return quote; } + /** + * Derives a raw key from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @returns The derived key. + */ async rawDeriveKey(path, subject) { try { if (!path || !subject) { @@ -1408,6 +1424,13 @@ var DeriveKeyProvider = class { throw error; } } + /** + * Derives an Ed25519 keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. + * @returns An object containing the derived keypair and attestation. + */ async deriveEd25519Keypair(path, subject, agentId) { try { if (!path || !subject) { @@ -1434,6 +1457,13 @@ var DeriveKeyProvider = class { throw error; } } + /** + * Derives an ECDSA keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. + * @returns An object containing the derived keypair and attestation. + */ async deriveEcdsaKeypair(path, subject, agentId) { try { if (!path || !subject) { @@ -1472,13 +1502,13 @@ var deriveKeyProvider = { try { const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; const solanaKeypair = await provider.deriveEd25519Keypair( - "/", secretSalt, + "solana", agentId ); const evmKeypair = await provider.deriveEcdsaKeypair( - "/", secretSalt, + "evm", agentId ); return JSON.stringify({ @@ -1511,7 +1541,7 @@ function hexToUint8Array(hex) { } const array = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) { - const byte = parseInt(hex.slice(i, i + 2), 16); + const byte = Number.parseInt(hex.slice(i, i + 2), 16); if (isNaN(byte)) { throw new Error("Invalid hex string"); } @@ -1532,18 +1562,26 @@ var remoteAttestationAction = { name: "REMOTE_ATTESTATION", similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"], description: "Generate a remote attestation to prove that the agent is running in a TEE", - handler: async (runtime, _message, _state, _options, callback) => { + handler: async (runtime, message, _state, _options, callback) => { try { - const agentId = runtime.agentId; + const attestationMessage = { + agentId: runtime.agentId, + timestamp: Date.now(), + message: { + userId: message.userId, + roomId: message.roomId, + content: message.content.text + } + }; const teeMode = runtime.getSetting("TEE_MODE"); const provider = new RemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation(agentId, "raw"); + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); const attestationData = hexToUint8Array(attestation.quote); const response = await uploadUint8Array(attestationData); const data = await response.json(); callback({ text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} - https://proof.t16z.com/reports/${data.checksum}`, +https://proof.t16z.com/reports/${data.checksum}`, action: "NONE" }); return true; @@ -1560,14 +1598,14 @@ var remoteAttestationAction = { { user: "{{user1}}", content: { - text: "If you are running in a TEE, generate a remote attestation" + text: "If you are running in a TEE, generate a remote attestation", + action: "REMOTE_ATTESTATION" } }, { user: "{{user2}}", content: { - text: "Of course, one second...", - action: "REMOTE_ATTESTATION" + text: "Of course, one second..." } } ] diff --git a/dist/index.js.map b/dist/index.js.map index 8164005..40b877d 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/providers/remoteAttestationProvider.ts","../src/types/tee.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/actions/remoteAttestation.ts","../src/index.ts"],"sourcesContent":["import {\n IAgentRuntime,\n Memory,\n Provider,\n State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { TdxQuoteResponse, TappdClient, TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\nimport { RemoteAttestationQuote, TEEMode } from \"../types/tee\";\n\nclass RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n elizaLogger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse =\n await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n elizaLogger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n elizaLogger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst remoteAttestationProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n elizaLogger.log(\"Generating attestation for: \", agentId);\n const attestation = await provider.generateAttestation(agentId, 'raw');\n return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`;\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n },\n};\n\nexport { remoteAttestationProvider, RemoteAttestationProvider };\n","export enum TEEMode {\n OFF = \"OFF\",\n LOCAL = \"LOCAL\", // For local development with simulator\n DOCKER = \"DOCKER\", // For docker development with simulator\n PRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n quote: string;\n timestamp: number;\n}\n","import {\n IAgentRuntime,\n Memory,\n Provider,\n State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { Keypair } from \"@solana/web3.js\";\nimport crypto from \"crypto\";\nimport { DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { PrivateKeyAccount, keccak256 } from \"viem\";\nimport { RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { TEEMode, RemoteAttestationQuote } from \"../types/tee\";\n\ninterface DeriveKeyAttestationData {\n agentId: string;\n publicKey: string;\n}\n\nclass DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n elizaLogger.log(\n \"Generating Remote Attestation Quote for Derive Key...\"\n );\n const quote = await this.raProvider.generateAttestation(reportdata);\n elizaLogger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n elizaLogger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n elizaLogger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n const hash = crypto.createHash(\"sha256\");\n hash.update(uint8ArrayDerivedKey);\n const seed = hash.digest();\n const seedArray = new Uint8Array(seed);\n const keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n elizaLogger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse =\n await this.client.deriveKey(path, subject);\n const hex = keccak256(deriveKeyResponse.asUint8Array());\n const keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n elizaLogger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\nconst deriveKeyProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new DeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n elizaLogger.error(\n \"Wallet secret salt is not configured in settings\"\n );\n return \"\";\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n \"/\",\n secretSalt,\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n \"/\",\n secretSalt,\n agentId\n );\n return JSON.stringify({\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n });\n } catch (error) {\n elizaLogger.error(\"Error creating PublicKey:\", error);\n return \"\";\n }\n } catch (error) {\n elizaLogger.error(\"Error in derive key provider:\", error.message);\n return `Failed to fetch derive key information: ${error instanceof Error ? error.message : \"Unknown error\"}`;\n }\n },\n};\n\nexport { deriveKeyProvider, DeriveKeyProvider };\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount(\n source: accountSource,\n): GetAccountReturnType {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters): SerializeSignatureReturnType {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType\n return hexToBytes(signature) as SerializeSignatureReturnType\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters): Promise> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray = T | readonly RecursiveArray[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp(\n bytes: RecursiveArray | RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType\n return cursor.bytes as ToRlpReturnType\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp(\n bytes: RecursiveArray,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp(\n hex: RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray | RecursiveArray,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization(\n parameters: HashAuthorizationParameters,\n): HashAuthorizationReturnType {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType\n return hash as HashAuthorizationReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters,\n): BlobsToCommitmentsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters,\n): blobsToProofsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType\n}\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\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 Sha256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash\n return toHex(bytes) as Sha256Hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters,\n): CommitmentToVersionedHashReturnType {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters,\n): CommitmentsToVersionedHashesReturnType {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters): ToBlobsReturnType {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType =\n | (to extends 'bytes' ? BlobSidecars : never)\n | (to extends 'hex' ? BlobSidecars : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters,\n): ToBlobSidecarsReturnType {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract\n : never),\n> = IsNever extends true\n ? string\n : IsNever extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType {\n if (transaction.type)\n return transaction.type as GetTransactionType\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial,\n ExactPartial &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = TransactionSerialized>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n>(\n parameters: SignTransactionParameters,\n): Promise> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n typeof domain?.chainId === 'number' && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record\n },\n results: Set = new Set(),\n): Set {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters,\n): Promise {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import type { IAgentRuntime, Memory, State, HandlerCallback } from \"@elizaos/core\";\nimport { RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { fetch, type BodyInit } from \"undici\";\n\nfunction hexToUint8Array(hex: string) {\n hex = hex.trim();\n if (!hex) {\n throw new Error(\"Invalid hex string\");\n }\n if (hex.startsWith(\"0x\")) {\n hex = hex.substring(2);\n }\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n const byte = parseInt(hex.slice(i, i + 2), 16);\n if (isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, 'quote.bin');\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\nexport const remoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n description: \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n _message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback,\n ) => {\n try {\n // Get the remote attestation of the agentId\n const agentId = runtime.agentId;\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const attestation = await provider.generateAttestation(agentId, 'raw');\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n callback({\n text: `Here's my 🧾 RA Quote 🫡\n https://proof.t16z.com/reports/${data.checksum}`,\n action: \"NONE\",\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n user: \"{{user1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n },\n },\n {\n user: \"{{user2}}\",\n content: {\n text: \"Of course, one second...\",\n action: \"REMOTE_ATTESTATION\",\n },\n }\n ],\n ],\n};","import { Plugin } from \"@elizaos/core\";\nimport { remoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nimport { deriveKeyProvider } from \"./providers/deriveKeyProvider\";\nimport { remoteAttestationAction } from \"./actions/remoteAttestation\";\n\nexport { DeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { RemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { RemoteAttestationQuote, TEEMode } from \"./types/tee\";\n\nexport const teePlugin: Plugin = {\n name: \"tee\",\n description:\n \"TEE plugin with actions to generate remote attestations and derive keys\",\n actions: [\n /* custom actions */\n remoteAttestationAction,\n ],\n evaluators: [\n /* custom evaluators */\n ],\n providers: [\n /* custom providers */\n remoteAttestationProvider,\n deriveKeyProvider,\n ],\n services: [\n /* custom services */\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKI;AAAA,OACG;AACP,SAA2B,mBAA2C;;;ACP/D,IAAK,UAAL,kBAAKA,aAAL;AACH,EAAAA,SAAA,SAAM;AACN,EAAAA,SAAA,WAAQ;AACR,EAAAA,SAAA,YAAS;AACT,EAAAA,SAAA,gBAAa;AAJL,SAAAA;AAAA,GAAA;;;ADUZ,IAAM,4BAAN,MAAgC;AAAA,EACpB;AAAA,EAER,YAAY,SAAkB;AAC1B,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACb;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;A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X,SAAS,OAAO;AACZ,cAAQ,MAAM,wCAAwC,KAAK;AAC3D,aAAO;AAAA,IACX;AAAA,EACJ;AAAA,EACA,UAAU,OAAO,aAA4B;AACzC,WAAO;AAAA,EACX;AAAA,EACA,UAAU;AAAA,IACN;AAAA,MACI;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,QACV;AAAA,MACJ;AAAA,MACA;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,UACN,QAAQ;AAAA,QACZ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;;;AChFO,IAAM,YAAoB;AAAA,EAC7B,MAAM;AAAA,EACN,aACI;AAAA,EACJ,SAAS;AAAA;AAAA,IAEL;AAAA,EACJ;AAAA,EACA,YAAY;AAAA;AAAA,EAEZ;AAAA,EACA,WAAW;AAAA;AAAA,IAEP;AAAA,IACA;AAAA,EACJ;AAAA,EACA,UAAU;AAAA;AAAA,EAEV;AACJ;","names":["TEEMode","elizaLogger","TappdClient","sha256","toBytes","sha256","size","size","blobs","commitments","proofs","v","struct","elizaLogger","TappdClient"]} \ No newline at end of file +{"version":3,"sources":["../src/providers/remoteAttestationProvider.ts","../src/types/tee.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/actions/remoteAttestation.ts","../src/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { type TdxQuoteResponse, TappdClient, type TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\nimport { type RemoteAttestationQuote, TEEMode, type RemoteAttestationMessage } from \"../types/tee\";\n\nclass RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n elizaLogger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse =\n await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n elizaLogger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n elizaLogger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst remoteAttestationProvider: Provider = {\n get: async (runtime: IAgentRuntime, message: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n userId: message.userId,\n roomId: message.roomId,\n content: message.content.text,\n }\n };\n elizaLogger.log(\"Generating attestation for: \", JSON.stringify(attestationMessage));\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`;\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n },\n};\n\nexport { remoteAttestationProvider, RemoteAttestationProvider };\n","export enum TEEMode {\n OFF = \"OFF\",\n LOCAL = \"LOCAL\", // For local development with simulator\n DOCKER = \"DOCKER\", // For docker development with simulator\n PRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n quote: string;\n timestamp: number;\n}\n\nexport interface DeriveKeyAttestationData {\n agentId: string;\n publicKey: string;\n subject?: string;\n}\n\nexport interface RemoteAttestationMessage {\n agentId: string;\n timestamp: number;\n message: {\n userId: string;\n roomId: string;\n content: string;\n }\n}","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { Keypair } from \"@solana/web3.js\";\nimport crypto from \"crypto\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { type PrivateKeyAccount, keccak256 } from \"viem\";\nimport { RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { TEEMode, type RemoteAttestationQuote, type DeriveKeyAttestationData } from \"../types/tee\";\n\nclass DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n elizaLogger.log(\n \"Generating Remote Attestation Quote for Derive Key...\"\n );\n const quote = await this.raProvider.generateAttestation(reportdata);\n elizaLogger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n elizaLogger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n elizaLogger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n const hash = crypto.createHash(\"sha256\");\n hash.update(uint8ArrayDerivedKey);\n const seed = hash.digest();\n const seedArray = new Uint8Array(seed);\n const keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n elizaLogger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse =\n await this.client.deriveKey(path, subject);\n const hex = keccak256(deriveKeyResponse.asUint8Array());\n const keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n elizaLogger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\nconst deriveKeyProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new DeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n elizaLogger.error(\n \"Wallet secret salt is not configured in settings\"\n );\n return \"\";\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n secretSalt,\n \"solana\",\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n secretSalt,\n \"evm\",\n agentId\n );\n return JSON.stringify({\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n });\n } catch (error) {\n elizaLogger.error(\"Error creating PublicKey:\", error);\n return \"\";\n }\n } catch (error) {\n elizaLogger.error(\"Error in derive key provider:\", error.message);\n return `Failed to fetch derive key information: ${error instanceof Error ? error.message : \"Unknown error\"}`;\n }\n },\n};\n\nexport { deriveKeyProvider, DeriveKeyProvider };\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount(\n source: accountSource,\n): GetAccountReturnType {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters): SerializeSignatureReturnType {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType\n return hexToBytes(signature) as SerializeSignatureReturnType\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters): Promise> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray = T | readonly RecursiveArray[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp(\n bytes: RecursiveArray | RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType\n return cursor.bytes as ToRlpReturnType\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp(\n bytes: RecursiveArray,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp(\n hex: RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray | RecursiveArray,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization(\n parameters: HashAuthorizationParameters,\n): HashAuthorizationReturnType {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType\n return hash as HashAuthorizationReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters,\n): BlobsToCommitmentsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters,\n): blobsToProofsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType\n}\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\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 Sha256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash\n return toHex(bytes) as Sha256Hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters,\n): CommitmentToVersionedHashReturnType {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters,\n): CommitmentsToVersionedHashesReturnType {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters): ToBlobsReturnType {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType =\n | (to extends 'bytes' ? BlobSidecars : never)\n | (to extends 'hex' ? BlobSidecars : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters,\n): ToBlobSidecarsReturnType {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract\n : never),\n> = IsNever extends true\n ? string\n : IsNever extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType {\n if (transaction.type)\n return transaction.type as GetTransactionType\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial,\n ExactPartial &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = TransactionSerialized>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n>(\n parameters: SignTransactionParameters,\n): Promise> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n typeof domain?.chainId === 'number' && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record\n },\n results: Set = new Set(),\n): Set {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters,\n): Promise {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import type { IAgentRuntime, Memory, State, HandlerCallback } from \"@elizaos/core\";\nimport { RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { fetch, type BodyInit } from \"undici\";\nimport type { RemoteAttestationMessage } from \"../types/tee\";\n\nfunction hexToUint8Array(hex: string) {\n hex = hex.trim();\n if (!hex) {\n throw new Error(\"Invalid hex string\");\n }\n if (hex.startsWith(\"0x\")) {\n hex = hex.substring(2);\n }\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n const byte = Number.parseInt(hex.slice(i, i + 2), 16);\n if (isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, 'quote.bin');\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\nexport const remoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n description: \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback,\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n userId: message.userId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n callback({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n action: \"NONE\",\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n user: \"{{user1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n action: \"REMOTE_ATTESTATION\",\n },\n },\n {\n user: \"{{user2}}\",\n content: {\n text: \"Of course, one second...\",\n },\n }\n ],\n ],\n};\n","import type { Plugin } from \"@elizaos/core\";\nimport { remoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nimport { deriveKeyProvider } from \"./providers/deriveKeyProvider\";\nimport { remoteAttestationAction } from \"./actions/remoteAttestation\";\n\nexport { DeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { RemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { RemoteAttestationQuote, TEEMode } from \"./types/tee\";\n\nexport const teePlugin: Plugin = {\n name: \"tee\",\n description:\n \"TEE plugin with actions to generate remote attestations and derive keys\",\n actions: [\n /* custom actions */\n remoteAttestationAction,\n ],\n evaluators: [\n /* custom evaluators */\n ],\n providers: [\n /* custom providers */\n remoteAttestationProvider,\n deriveKeyProvider,\n ],\n services: [\n /* custom services */\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKI;AAAA,OACG;AACP,SAAgC,mBAAgD;;;ACPzE,IAAK,UAAL,kBAAKA,aAAL;AACH,EAAAA,SAAA,SAAM;AACN,EAAAA,SAAA,WAAQ;AACR,EAAAA,SAAA,YAAS;AACT,EAAAA,SAAA,gBAAa;AAJL,SAAAA;AAAA,GAAA;;;ADUZ,IAAM,4BAAN,MAAgC;AAAA,EACpB;AAAA,EAER,YAAY,SAAkB;AAC1B,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACb;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,cAAM,IAAI;AAAA,UACN,qBAAqB,OAAO;AAAA,QAChC;AAAA,IACR;AAEA,SAAK,SAAS,WAAW,IAAI,YAAY,QAAQ,IAAI,IAAI,YAAY;AAAA,EACzE;AAAA,EAEA,MAAM,oBACF,YACA,eAC+B;AAC/B,QAAI;AACA,kBAAY,IAAI,gCAAgC,UAAU;AAC1D,YAAM,WACF,MAAM,KAAK,OAAO,SAAS,YAAY,aAAa;AACxD,YAAM,QAAQ,SAAS,YAAY;AACnC,kBAAY;AAAA,QACR,UAAU,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,MAClF;AACA,YAAM,QAAgC;AAAA,QAClC,OAAO,SAAS;AAAA,QAChB,WAAW,KAAK,IAAI;AAAA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;AAAA,IACX,SAAS,OAAO;AACZ,cAAQ,MAAM,wCAAwC,KAAK;AAC3D,aAAO;AAAA,IACX;AAAA,EACJ;AAAA,EACA,UAAU,OAAO,aAA4B;AACzC,WAAO;AAAA,EACX;AAAA,EACA,UAAU;AAAA,IACN;AAAA,MACI;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,UACN,QAAQ;AAAA,QACZ;AAAA,MACJ;AAAA,MACA;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;;;AC3FO,IAAM,YAAoB;AAAA,EAC7B,MAAM;AAAA,EACN,aACI;AAAA,EACJ,SAAS;AAAA;AAAA,IAEL;AAAA,EACJ;AAAA,EACA,YAAY;AAAA;AAAA,EAEZ;AAAA,EACA,WAAW;AAAA;AAAA,IAEP;AAAA,IACA;AAAA,EACJ;AAAA,EACA,UAAU;AAAA;AAAA,EAEV;AACJ;","names":["TEEMode","elizaLogger","TappdClient","sha256","toBytes","sha256","size","size","blobs","commitments","proofs","v","struct","elizaLogger","TappdClient"]} \ No newline at end of file From 1b8eb5809968fb5e0b92b32a4d9335097597d811 Mon Sep 17 00:00:00 2001 From: mavisakalyan <55106546+mavisakalyan@users.noreply.github.com> Date: Fri, 7 Feb 2025 19:33:07 +0400 Subject: [PATCH 10/39] Update banner for tee --- images/banner.jpg | Bin 0 -> 12636 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 images/banner.jpg diff --git a/images/banner.jpg b/images/banner.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a80d90701fd21f3bd00f4690fc44771e94a4ecd3 GIT binary patch literal 12636 zcmbVy2~-raO5FSxroIE8vBUh7_F>U&+fo?C3opRGmPao)(7#bHCXB?W5IX!0n z?2K{qN9m``&z{mR-7R8}CcL13!A#@KjNHkZf|)aB&FNn-(CyF0`_u28#Q|=bKda5HCaj--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357ff322ced4ea31ae14276399d3369762 Mon Sep 17 00:00:00 2001 From: mavisakalyan <55106546+mavisakalyan@users.noreply.github.com> Date: Fri, 7 Feb 2025 19:33:08 +0400 Subject: [PATCH 11/39] Update logo for tee --- images/logo.jpg | Bin 0 -> 6162 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 images/logo.jpg diff --git a/images/logo.jpg b/images/logo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fe96f2b7ad81a77c1ac0cee83cbf9d937b0f7f89 GIT binary patch literal 6162 zcmaJ_2|SeB`#WQd`>$>OXO7aKc@DK~;m zVW`omEE-LNqRUWY>aujSSS){rDn)~)p`}jKRj2Dv=^FZ)41Jmw)V@| zf1M8N8Onc+D>^z_Em~8J8xf#RXD}G*G!1nP4Jsx<<;8L$ePgH`p29Z^W^5iSA}BmE zh|8fYTJ&XdqaqFEF=zjdA}rj-=DXp41uQIVF|;qzyhwZYKW_Z1G|wS6oULxp=5eDU zSZqvO;hQoB-+xcED2REZZyOPWt&4A{8J86m#^yv?nHkDsBWiv@e)=>9U4zZirc)VO z{(e*~U#2Eik49%u^)xk^emYtj+H9KkH#`5PPuDTkG||)AWM+z4qHi`gp_$M(o0#ft z(xaK^=+Vr+=~{7kk-i)j``g?>*xX-rP5x6?-!y{l8_A7u;BrI1C4yZbH5NDCIVR4oI4%&dvVENMgm<*aWRZo}ArfO;F z`YlGTN!4cPF*SAkd}$gwbosCPem}tXccx+-ER67P-srPvdj5L8T5PH=gQiPm_-Qez z3{5{BsvZl=DwZ})TiahlULA8$eKB)>$fR#9EIk*S-%A7Qd@n9G2dk(EtaKKp!16Bz z0sI75i9!qgAQiySB4J+`2V*}Rj1lfD5pZ~na0CKDNJxl45Edp9g@s9rwCp=Um^>bb z7siH3L}B6&Bi}{-yRjeuWFmxZ8#sszU^0XwLkrEI5I~C@?DL%!2ot_2LF9FGyooQ2BM9xpG`A;Lu2?DYhxnaC{8di5&QhzT_ea*; z9o=bAxJ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3^AYLJa5^4&6R5iR7AWIQCdNTFW~MFC_s;}>?Ev(I|1*3q^>7BQM6F=sv@9( z-2<~lI9Oca0GM|Z0)cp#K*cW4;F#=+hCkpM0$?B@gA5!{ zKu2ZaY$6PRs*EMc9T5h0qQ6qi?TZ|l7fs;CVX`AaFQS|)lE`*L5Ml$xO}Tgp9H+XEAg+MFhNoJSl)eF78r^0Sb<9P`?;}&n%*p!aCVxP>M(Z3lJ`>hKkHlU32KH8SNT3B`h)Tj}2&#Pv zP{RS7O}YWPV6i1nc$jV2OE5@_Km0Ka|lMF|zI zfWcW15e@=~LMMW-rI8yJ-w4+L5@Oc{#0csWC`#b2F`*#&6b7)n1BQuDQ}dIt?AQ

t^G literal 0 HcmV?d00001 From 90f25b39b75be0f14adfcbcb7687c9f5a3e4acc9 Mon Sep 17 00:00:00 2001 From: Carlos V Date: Wed, 12 Feb 2025 13:37:42 -0500 Subject: [PATCH 12/39] chore: update plugin configuration and dependencies --- .DS_Store | Bin 0 -> 6148 bytes .gitignore | 2 + .turbo/turbo-build.log | 59 +++++----- dist/_esm-FVHF6KDD.js.map | 1 - dist/{_esm-FVHF6KDD.js => _esm-L4OBJJWB.js} | 10 +- dist/_esm-L4OBJJWB.js.map | 1 + package.json | 117 ++++++++++++-------- src/.DS_Store | Bin 0 -> 6148 bytes 8 files changed, 107 insertions(+), 83 deletions(-) create mode 100644 .DS_Store create mode 100644 .gitignore delete mode 100644 dist/_esm-FVHF6KDD.js.map rename dist/{_esm-FVHF6KDD.js => _esm-L4OBJJWB.js} (99%) create mode 100644 dist/_esm-L4OBJJWB.js.map create mode 100644 src/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..44062b7bb76b86ff74bcd6e4940bc082dde4e60c GIT binary patch literal 6148 zcmeHKJx?1!5PcgTjuTQ)1Sv(3PU&bOXedH+0jHp|WGOAg*fNoPoQ3WFBq)+!kw}(O zqWps>6cnUSmo}oNphS7IyE^asOVC6J?O40-ZfEA^-MhP8F95YQXs!cG04i*P(NlI) zO#IR&?2#RLNmO!;PJ6w+pQYW2$S@ET2nyUs1?1a}@EUD=MBn><7yfRzzBH>=8=b7d zv5I82XzTAAC7whtSKm2)pV&0#b*LJzyCf?<(hTnyEiO=i^`@VABS0j(h z>BnWEnay(}D}Y-MG4C`wo7c&x*r5`&=+ z3Iqjw1xn_0N!I^&v-kggQaB3=1O*jPPeU$AMTFO~yhVlg+!5nA{opk)YMP~g8R@DC5d@!0?X literal 0 HcmV?d00001 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c98e331 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +.turbo diff --git a/.turbo/turbo-build.log b/.turbo/turbo-build.log index 665fb89..09bfe85 100644 --- a/.turbo/turbo-build.log +++ b/.turbo/turbo-build.log @@ -1,30 +1,29 @@ - - -> @elizaos/plugin-tee@0.1.8+build.1 build /Users/a/eliza-wrangler/packages/plugin-tee -> tsup --format esm --dts - -CLI Building entry: src/index.ts -CLI Using tsconfig: tsconfig.json -CLI tsup v8.3.5 -CLI Using tsup config: /Users/a/eliza-wrangler/packages/plugin-tee/tsup.config.ts -CLI Target: esnext -CLI Cleaning output folder -ESM Build start -ESM dist/secp256k1-QUTB2QC2.js 237.00 B -ESM dist/ccip-IAE5UWYX.js 290.00 B -ESM dist/chunk-4L6P6TY5.js 80.02 KB -ESM dist/chunk-KSHJJL6X.js 131.11 KB -ESM dist/index.js 49.07 KB -ESM dist/chunk-PR4QN5HX.js 1.87 KB -ESM dist/_esm-FVHF6KDD.js 130.62 KB -ESM dist/ccip-IAE5UWYX.js.map 71.00 B -ESM dist/secp256k1-QUTB2QC2.js.map 71.00 B -ESM dist/index.js.map 138.45 KB -ESM dist/chunk-4L6P6TY5.js.map 202.99 KB -ESM dist/_esm-FVHF6KDD.js.map 211.12 KB -ESM dist/chunk-KSHJJL6X.js.map 386.85 KB -ESM dist/chunk-PR4QN5HX.js.map 71.00 B -ESM ⚡️ Build success in 356ms -DTS Build start -DTS ⚡️ Build success in 5753ms -DTS dist/index.d.ts 1.37 KB + +> @elizaos/plugin-tee@0.1.9 build /Users/gdesign/developer-projects/laborales/upstreet/eliza-last/eliza/packages/plugin-tee +> tsup --format esm --dts + +CLI Building entry: src/index.ts +CLI Using tsconfig: tsconfig.json +CLI tsup v8.3.5 +CLI Using tsup config: /Users/gdesign/developer-projects/laborales/upstreet/eliza-last/eliza/packages/plugin-tee/tsup.config.ts +CLI Target: esnext +CLI Cleaning output folder +ESM Build start +ESM dist/index.js 50.74 KB +ESM dist/secp256k1-QUTB2QC2.js 237.00 B +ESM dist/ccip-MMGH6DXX.js 290.00 B +ESM dist/_esm-L4OBJJWB.js 130.56 KB +ESM dist/chunk-NTU6R7BC.js 131.39 KB +ESM dist/chunk-PR4QN5HX.js 1.87 KB +ESM dist/chunk-4L6P6TY5.js 80.02 KB +ESM dist/chunk-PR4QN5HX.js.map 71.00 B +ESM dist/chunk-NTU6R7BC.js.map 387.13 KB +ESM dist/chunk-4L6P6TY5.js.map 202.99 KB +ESM dist/index.js.map 141.36 KB +ESM dist/secp256k1-QUTB2QC2.js.map 71.00 B +ESM dist/ccip-MMGH6DXX.js.map 71.00 B +ESM dist/_esm-L4OBJJWB.js.map 211.08 KB +ESM ⚡️ Build success in 491ms +DTS Build start +DTS ⚡️ Build success in 4647ms +DTS dist/index.d.ts 2.57 KB diff --git a/dist/_esm-FVHF6KDD.js.map b/dist/_esm-FVHF6KDD.js.map deleted file mode 100644 index 83ff82e..0000000 --- a/dist/_esm-FVHF6KDD.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../node_modules/ws/lib/stream.js","../../../node_modules/ws/lib/constants.js","../../../node_modules/node-gyp-build/node-gyp-build.js","../../../node_modules/node-gyp-build/index.js","../../../node_modules/bufferutil/fallback.js","../../../node_modules/bufferutil/index.js","../../../node_modules/ws/lib/buffer-util.js","../../../node_modules/ws/lib/limiter.js","../../../node_modules/ws/lib/permessage-deflate.js","../../../node_modules/ws/node_modules/utf-8-validate/fallback.js","../../../node_modules/ws/node_modules/utf-8-validate/index.js","../../../node_modules/ws/lib/validation.js","../../../node_modules/ws/lib/receiver.js","../../../node_modules/ws/lib/sender.js","../../../node_modules/ws/lib/event-target.js","../../../node_modules/ws/lib/extension.js","../../../node_modules/ws/lib/websocket.js","../../../node_modules/ws/lib/subprotocol.js","../../../node_modules/ws/lib/websocket-server.js","../../../node_modules/ws/wrapper.mjs","../../../node_modules/isows/utils.ts","../../../node_modules/isows/index.ts"],"sourcesContent":["'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/-\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of \n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","export function getNativeWebSocket() {\n if (typeof WebSocket !== \"undefined\") return WebSocket;\n if (typeof global.WebSocket !== \"undefined\") return global.WebSocket;\n if (typeof window.WebSocket !== \"undefined\") return window.WebSocket;\n if (typeof self.WebSocket !== \"undefined\") return self.WebSocket;\n throw new Error(\"`WebSocket` is not supported in this environment\");\n}\n","import * as WebSocket_ from \"ws\";\nimport { getNativeWebSocket } from \"./utils.js\";\n\nexport const WebSocket = (() => {\n try {\n return getNativeWebSocket();\n } catch {\n if (WebSocket_.WebSocket) return WebSocket_.WebSocket;\n return WebSocket_;\n }\n})();\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,EAAE,OAAO,IAAI,UAAQ,QAAQ;AAQnC,aAAS,UAAU,QAAQ;AACzB,aAAO,KAAK,OAAO;AAAA,IACrB;AAOA,aAAS,cAAc;AACrB,UAAI,CAAC,KAAK,aAAa,KAAK,eAAe,UAAU;AACnD,aAAK,QAAQ;AAAA,MACf;AAAA,IACF;AAQA,aAAS,cAAc,KAAK;AAC1B,WAAK,eAAe,SAAS,aAAa;AAC1C,WAAK,QAAQ;AACb,UAAI,KAAK,cAAc,OAAO,MAAM,GAAG;AAErC,aAAK,KAAK,SAAS,GAAG;AAAA,MACxB;AAAA,IACF;AAUA,aAASA,uBAAsB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qBAAkB;AAChC,MAAI,OAAO,cAAc;AAAa,WAAO;AAC7C,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,KAAK,cAAc;AAAa,WAAO,KAAK;AACvD,QAAM,IAAI,MAAM,kDAAkD;AACpE;;;ACHO,IAAMC,cAAa,MAAK;AAC7B,MAAI;AACF,WAAO,mBAAkB;EAC3B,QAAQ;AACN,QAAe,iBAAAA;AAAW,aAAkB,iBAAAA;AAC5C,WAAO;EACT;AACF,GAAE;","names":["createWebSocketStream","err","dir","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","Receiver","Sender","Receiver","Sender","WebSocket","key","protocol","WebSocket","WebSocketServer","Receiver","Sender","WebSocket","WebSocketServer","createWebSocketStream","WebSocket","WebSocket"]} \ No newline at end of file diff --git a/dist/_esm-FVHF6KDD.js b/dist/_esm-L4OBJJWB.js similarity index 99% rename from dist/_esm-FVHF6KDD.js rename to dist/_esm-L4OBJJWB.js index d794ed1..b53bc10 100644 --- a/dist/_esm-FVHF6KDD.js +++ b/dist/_esm-L4OBJJWB.js @@ -840,9 +840,9 @@ var require_permessage_deflate = __commonJS({ } }); -// ../../node_modules/ws/node_modules/utf-8-validate/fallback.js +// ../../node_modules/utf-8-validate/fallback.js var require_fallback2 = __commonJS({ - "../../node_modules/ws/node_modules/utf-8-validate/fallback.js"(exports, module) { + "../../node_modules/utf-8-validate/fallback.js"(exports, module) { "use strict"; function isValidUTF8(buf) { const len = buf.length; @@ -877,9 +877,9 @@ var require_fallback2 = __commonJS({ } }); -// ../../node_modules/ws/node_modules/utf-8-validate/index.js +// ../../node_modules/utf-8-validate/index.js var require_utf_8_validate = __commonJS({ - "../../node_modules/ws/node_modules/utf-8-validate/index.js"(exports, module) { + "../../node_modules/utf-8-validate/index.js"(exports, module) { "use strict"; try { module.exports = require_node_gyp_build2()(__dirname); @@ -3910,4 +3910,4 @@ var WebSocket3 = (() => { export { WebSocket3 as WebSocket }; -//# sourceMappingURL=_esm-FVHF6KDD.js.map \ No newline at end of file +//# sourceMappingURL=_esm-L4OBJJWB.js.map \ No newline at end of file diff --git a/dist/_esm-L4OBJJWB.js.map b/dist/_esm-L4OBJJWB.js.map new file mode 100644 index 0000000..74eb313 --- /dev/null +++ b/dist/_esm-L4OBJJWB.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/ws/lib/stream.js","../../../node_modules/ws/lib/constants.js","../../../node_modules/node-gyp-build/node-gyp-build.js","../../../node_modules/node-gyp-build/index.js","../../../node_modules/bufferutil/fallback.js","../../../node_modules/bufferutil/index.js","../../../node_modules/ws/lib/buffer-util.js","../../../node_modules/ws/lib/limiter.js","../../../node_modules/ws/lib/permessage-deflate.js","../../../node_modules/utf-8-validate/fallback.js","../../../node_modules/utf-8-validate/index.js","../../../node_modules/ws/lib/validation.js","../../../node_modules/ws/lib/receiver.js","../../../node_modules/ws/lib/sender.js","../../../node_modules/ws/lib/event-target.js","../../../node_modules/ws/lib/extension.js","../../../node_modules/ws/lib/websocket.js","../../../node_modules/ws/lib/subprotocol.js","../../../node_modules/ws/lib/websocket-server.js","../../../node_modules/ws/wrapper.mjs","../../../node_modules/isows/utils.ts","../../../node_modules/isows/index.ts"],"sourcesContent":["'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/-\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of \n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","export function getNativeWebSocket() {\n if (typeof WebSocket !== \"undefined\") return WebSocket;\n if (typeof global.WebSocket !== \"undefined\") return global.WebSocket;\n if (typeof window.WebSocket !== \"undefined\") return window.WebSocket;\n if (typeof self.WebSocket !== \"undefined\") return self.WebSocket;\n throw new Error(\"`WebSocket` is not supported in this environment\");\n}\n","import * as WebSocket_ from \"ws\";\nimport { getNativeWebSocket } from \"./utils.js\";\n\nexport const WebSocket = (() => {\n try {\n return getNativeWebSocket();\n } catch {\n if (WebSocket_.WebSocket) return WebSoc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O,cAAc,eAAe,GAAG;AACzC,cAAM,MAAM,IAAI,MAAM,OAAO;AAC7B,cAAM,kBAAkB,KAAK,iCAAiC;AAE9D,eAAO,KAAK,iBAAiB,KAAK,QAAQ,GAAG;AAAA,MAC/C,OAAO;AACL,uBAAe,QAAQ,MAAM,OAAO;AAAA,MACtC;AAAA,IACF;AAAA;AAAA;;;AC3hBA;AAAA;AAAA,kCAAAC;AAAA,EAAA,4BAAAC;AAAA,EAAA,kCAAAC;AAAA,EAAA,+CAAAC;AAAA,EAAA,2CAAAC;AAAA,EAAA;AAAA;AAAA,oBAAkC;AAClC,sBAAqB;AACrB,oBAAmB;AACnB,uBAAsB;AACtB,8BAA4B;AAG5B,IAAO,kBAAQ,iBAAAC;;;ACPT,SAAU,qBAAkB;AAChC,MAAI,OAAO,cAAc;AAAa,WAAO;AAC7C,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,KAAK,cAAc;AAAa,WAAO,KAAK;AACvD,QAAM,IAAI,MAAM,kDAAkD;AACpE;;;ACHO,IAAMC,cAAa,MAAK;AAC7B,MAAI;AACF,WAAO,mBAAkB;EAC3B,QAAQ;AACN,QAAe,iBAAAA;AAAW,aAAkB,iBAAAA;AAC5C,WAAO;EACT;AACF,GAAE;","names":["createWebSocketStream","err","dir","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","Receiver","Sender","Receiver","Sender","WebSocket","key","protocol","WebSocket","WebSocketServer","Receiver","Sender","WebSocket","WebSocketServer","createWebSocketStream","WebSocket","WebSocket"]} \ No newline at end of file diff --git a/package.json b/package.json index 9744bd5..eb60f2b 100644 --- a/package.json +++ b/package.json @@ -1,48 +1,71 @@ { - "name": "@elizaos/plugin-tee", - "version": "0.1.9", - "type": "module", - "main": "dist/index.js", - "module": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - "./package.json": "./package.json", - ".": { - "import": { - "@elizaos/source": "./src/index.ts", - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } - } - }, - "files": [ - "dist" - ], - "dependencies": { - "@elizaos/core": "workspace:*", - "@phala/dstack-sdk": "0.1.7", - "@solana/spl-token": "0.4.9", - "@solana/web3.js": "1.95.8", - "bignumber.js": "9.1.2", - "bs58": "6.0.0", - "node-cache": "5.1.2", - "pumpdotfun-sdk": "1.3.2", - "tsup": "8.3.5" - }, - "devDependencies": { - "@biomejs/biome": "1.5.3", - "tsup": "^8.3.5" - }, - "scripts": { - "build": "tsup --format esm --dts", - "dev": "tsup --format esm --dts --watch", - "test": "vitest run", - "lint": "biome check src/", - "lint:fix": "biome check --apply src/", - "format": "biome format src/", - "format:fix": "biome format --write src/" - }, - "peerDependencies": { - "whatwg-url": "7.1.0" - } -} + "name": "@elizaos/plugin-tee", + "version": "0.1.9", + "type": "module", + "main": "dist/index.js", + "module": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "@elizaos/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "dependencies": { + "@phala/dstack-sdk": "0.1.7", + "@solana/spl-token": "0.4.9", + "@solana/web3.js": "1.95.8", + "bignumber.js": "9.1.2", + "bs58": "6.0.0", + "node-cache": "5.1.2", + "pumpdotfun-sdk": "1.3.2", + "tsup": "8.3.5" + }, + "devDependencies": { + "@biomejs/biome": "1.5.3", + "tsup": "^8.3.5" + }, + "scripts": { + "build": "tsup --format esm --dts", + "dev": "tsup --format esm --dts --watch", + "test": "vitest run", + "lint": "biome check src/", + "lint:fix": "biome check --apply src/", + "format": "biome format src/", + "format:fix": "biome format --write src/" + }, + "peerDependencies": { + "whatwg-url": "7.1.0" + }, + "agentConfig": { + "pluginType": "elizaos:client:1.0.0", + "pluginParameters": { + "TEE_MODE": { + "type": "string", + "enum": [ + "sgx", + "nitro", + "disabled" + ], + "description": "Trusted Execution Environment mode" + }, + "WALLET_SECRET_SALT": { + "type": "string", + "minLength": 1, + "description": "Salt for wallet secret generation" + }, + "BIRDEYE_API_KEY": { + "type": "string", + "minLength": 1, + "description": "API key for Birdeye service" + } + } + } +} \ No newline at end of file diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..4614bd24994135a65594c8a52917e6001c0a4598 GIT binary patch literal 6148 zcmeHKOHRWu5FM8yQUOwzUFHhCK`7w_-Lil-rBrH2#7|-uiHmRo#0A)L0>lAWathwe zxM@NHLPA0a%}DlhCeQZEOBCBgf?=wdk^ zj;C3JZHd3=0KdB}I;JUI(t;}QFU?i%?n#r8W^p`OW)s{A9-jAKZttJ=+E~dqSotY` zEvwo1JER`vbPg@oP?XRNZU0TJSciA*tg5cZ*HTx@cxkrQ_BFGvPfXc_S2xf&`>3n4 zfUe5js-D4Hsi($R>u6`x=NEr4iG?{}4wwT!asX>KN3gAEwK-r8m;j1g(5Ntr(J>C)%hca)9%QJo)>v66tz1!nHl5wnVmnO zIKM-3q0q@iidLHg=0M$n4ZZC1`hW2G`M=)DuFL^*;9oi5y74$3;gS5>+ITo#YeSSH p6b|MUie(oxWGM!hm*N461o9y_fRV>S5gCMS1jGib%z Date: Wed, 12 Feb 2025 13:38:01 -0500 Subject: [PATCH 13/39] chore: update plugin dist --- tsup.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tsup.config.ts b/tsup.config.ts index 153f665..f6f7876 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -7,6 +7,7 @@ export default defineConfig({ clean: true, format: ["esm"], // Ensure you're targeting CommonJS external: [ + "@elizaos/core", "dotenv", // Externalize dotenv to prevent bundling "fs", // Externalize fs to use Node.js built-in module "path", // Externalize other built-ins if necessary From 1987bd21bd840c54639df036092f3d723f1875c4 Mon Sep 17 00:00:00 2001 From: Carlos V Date: Mon, 17 Feb 2025 08:44:10 -0500 Subject: [PATCH 14/39] fix: update package name to match repository name --- package.json | 136 +++++++++++++++++++++++++-------------------------- 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/package.json b/package.json index eb60f2b..2d96ec7 100644 --- a/package.json +++ b/package.json @@ -1,71 +1,71 @@ { - "name": "@elizaos/plugin-tee", - "version": "0.1.9", - "type": "module", - "main": "dist/index.js", - "module": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - "./package.json": "./package.json", - ".": { - "import": { - "@elizaos/source": "./src/index.ts", - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } + "name": "@elizaos-plugins/plugin-tee", + "version": "0.1.9", + "type": "module", + "main": "dist/index.js", + "module": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "@elizaos/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "dependencies": { + "@phala/dstack-sdk": "0.1.7", + "@solana/spl-token": "0.4.9", + "@solana/web3.js": "1.95.8", + "bignumber.js": "9.1.2", + "bs58": "6.0.0", + "node-cache": "5.1.2", + "pumpdotfun-sdk": "1.3.2", + "tsup": "8.3.5" + }, + "devDependencies": { + "@biomejs/biome": "1.5.3", + "tsup": "^8.3.5" + }, + "scripts": { + "build": "tsup --format esm --dts", + "dev": "tsup --format esm --dts --watch", + "test": "vitest run", + "lint": "biome check src/", + "lint:fix": "biome check --apply src/", + "format": "biome format src/", + "format:fix": "biome format --write src/" + }, + "peerDependencies": { + "whatwg-url": "7.1.0" + }, + "agentConfig": { + "pluginType": "elizaos:client:1.0.0", + "pluginParameters": { + "TEE_MODE": { + "type": "string", + "enum": [ + "sgx", + "nitro", + "disabled" + ], + "description": "Trusted Execution Environment mode" + }, + "WALLET_SECRET_SALT": { + "type": "string", + "minLength": 1, + "description": "Salt for wallet secret generation" + }, + "BIRDEYE_API_KEY": { + "type": "string", + "minLength": 1, + "description": "API key for Birdeye service" + } + } } - }, - "files": [ - "dist" - ], - "dependencies": { - "@phala/dstack-sdk": "0.1.7", - "@solana/spl-token": "0.4.9", - "@solana/web3.js": "1.95.8", - "bignumber.js": "9.1.2", - "bs58": "6.0.0", - "node-cache": "5.1.2", - "pumpdotfun-sdk": "1.3.2", - "tsup": "8.3.5" - }, - "devDependencies": { - "@biomejs/biome": "1.5.3", - "tsup": "^8.3.5" - }, - "scripts": { - "build": "tsup --format esm --dts", - "dev": "tsup --format esm --dts --watch", - "test": "vitest run", - "lint": "biome check src/", - "lint:fix": "biome check --apply src/", - "format": "biome format src/", - "format:fix": "biome format --write src/" - }, - "peerDependencies": { - "whatwg-url": "7.1.0" - }, - "agentConfig": { - "pluginType": "elizaos:client:1.0.0", - "pluginParameters": { - "TEE_MODE": { - "type": "string", - "enum": [ - "sgx", - "nitro", - "disabled" - ], - "description": "Trusted Execution Environment mode" - }, - "WALLET_SECRET_SALT": { - "type": "string", - "minLength": 1, - "description": "Salt for wallet secret generation" - }, - "BIRDEYE_API_KEY": { - "type": "string", - "minLength": 1, - "description": "API key for Birdeye service" - } - } - } } \ No newline at end of file From fecca54c640a1d1b0069198483624ef62a0dd3be Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Thu, 15 May 2025 17:26:37 -0500 Subject: [PATCH 15/39] port plugin-tee v1.x --- .gitignore | 1 + .turbo/turbo-build.log | 29 - LICENSE | 21 + README.md | 296 +- __tests__/deriveKey.test.ts | 111 - __tests__/remoteAttestation.test.ts | 81 - __tests__/remoteAttestationAction.test.ts | 103 - __tests__/timeout.test.ts | 117 - biome.json | 41 - bun.lockb | Bin 0 -> 164895 bytes dist/_esm-L4OBJJWB.js | 3913 ------------------- dist/_esm-L4OBJJWB.js.map | 1 - dist/ccip-MMGH6DXX.js | 14 - dist/ccip-MMGH6DXX.js.map | 1 - dist/chunk-4L6P6TY5.js | 2556 ------------- dist/chunk-4L6P6TY5.js.map | 1 - dist/chunk-NTU6R7BC.js | 4019 -------------------- dist/chunk-NTU6R7BC.js.map | 1 - dist/chunk-PR4QN5HX.js | 43 - dist/chunk-PR4QN5HX.js.map | 1 - dist/index.d.ts | 61 - dist/index.js | 1764 ++------- dist/index.js.map | 2 +- dist/secp256k1-QUTB2QC2.js | 14 - dist/secp256k1-QUTB2QC2.js.map | 1 - images/banner.jpg | Bin 12636 -> 0 bytes images/logo.jpg | Bin 6162 -> 0 bytes package.json | 110 +- src/.DS_Store | Bin 6148 -> 0 bytes src/__tests__/deriveKey.test.ts | 111 + src/__tests__/remoteAttestation.test.ts | 83 + src/__tests__/timeout.test.ts | 113 + src/actions/remoteAttestation.ts | 101 - src/actions/remoteAttestationAction.ts | 137 + src/index.ts | 89 +- src/providers/base.ts | 36 + src/providers/deriveKeyProvider.ts | 442 +-- src/providers/remoteAttestationProvider.ts | 202 +- src/providers/walletProvider.ts | 326 -- src/types.ts | 10 + src/types/tee.ts | 27 - src/utils.ts | 41 + src/vendors/index.ts | 17 + src/vendors/phala.ts | 58 + src/vendors/types.ts | 24 + tsconfig.build.json | 13 + tsconfig.json | 19 +- tsup.config.ts | 55 +- 48 files changed, 1548 insertions(+), 13658 deletions(-) delete mode 100644 .turbo/turbo-build.log create mode 100644 LICENSE delete mode 100644 __tests__/deriveKey.test.ts delete mode 100644 __tests__/remoteAttestation.test.ts delete mode 100644 __tests__/remoteAttestationAction.test.ts delete mode 100644 __tests__/timeout.test.ts delete mode 100644 biome.json create mode 100755 bun.lockb delete mode 100644 dist/_esm-L4OBJJWB.js delete mode 100644 dist/_esm-L4OBJJWB.js.map delete mode 100644 dist/ccip-MMGH6DXX.js delete mode 100644 dist/ccip-MMGH6DXX.js.map delete mode 100644 dist/chunk-4L6P6TY5.js delete mode 100644 dist/chunk-4L6P6TY5.js.map delete mode 100644 dist/chunk-NTU6R7BC.js delete mode 100644 dist/chunk-NTU6R7BC.js.map delete mode 100644 dist/chunk-PR4QN5HX.js delete mode 100644 dist/chunk-PR4QN5HX.js.map delete mode 100644 dist/index.d.ts delete mode 100644 dist/secp256k1-QUTB2QC2.js delete mode 100644 dist/secp256k1-QUTB2QC2.js.map delete mode 100644 images/banner.jpg delete mode 100644 images/logo.jpg delete mode 100644 src/.DS_Store create mode 100644 src/__tests__/deriveKey.test.ts create mode 100644 src/__tests__/remoteAttestation.test.ts create mode 100644 src/__tests__/timeout.test.ts delete mode 100644 src/actions/remoteAttestation.ts create mode 100644 src/actions/remoteAttestationAction.ts create mode 100644 src/providers/base.ts delete mode 100644 src/providers/walletProvider.ts create mode 100644 src/types.ts delete mode 100644 src/types/tee.ts create mode 100644 src/utils.ts create mode 100644 src/vendors/index.ts create mode 100644 src/vendors/phala.ts create mode 100644 src/vendors/types.ts create mode 100644 tsconfig.build.json diff --git a/.gitignore b/.gitignore index c98e331..dfdbf1f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules .turbo +dist \ No newline at end of file diff --git a/.turbo/turbo-build.log b/.turbo/turbo-build.log deleted file mode 100644 index 09bfe85..0000000 --- a/.turbo/turbo-build.log +++ /dev/null @@ -1,29 +0,0 @@ - -> @elizaos/plugin-tee@0.1.9 build /Users/gdesign/developer-projects/laborales/upstreet/eliza-last/eliza/packages/plugin-tee -> tsup --format esm --dts - -CLI Building entry: src/index.ts -CLI Using tsconfig: tsconfig.json -CLI tsup v8.3.5 -CLI Using tsup config: /Users/gdesign/developer-projects/laborales/upstreet/eliza-last/eliza/packages/plugin-tee/tsup.config.ts -CLI Target: esnext -CLI Cleaning output folder -ESM Build start -ESM dist/index.js 50.74 KB -ESM dist/secp256k1-QUTB2QC2.js 237.00 B -ESM dist/ccip-MMGH6DXX.js 290.00 B -ESM dist/_esm-L4OBJJWB.js 130.56 KB -ESM dist/chunk-NTU6R7BC.js 131.39 KB -ESM dist/chunk-PR4QN5HX.js 1.87 KB -ESM dist/chunk-4L6P6TY5.js 80.02 KB -ESM dist/chunk-PR4QN5HX.js.map 71.00 B -ESM dist/chunk-NTU6R7BC.js.map 387.13 KB -ESM dist/chunk-4L6P6TY5.js.map 202.99 KB -ESM dist/index.js.map 141.36 KB -ESM dist/secp256k1-QUTB2QC2.js.map 71.00 B -ESM dist/ccip-MMGH6DXX.js.map 71.00 B -ESM dist/_esm-L4OBJJWB.js.map 211.08 KB -ESM ⚡️ Build success in 491ms -DTS Build start -DTS ⚡️ Build success in 4647ms -DTS dist/index.d.ts 2.57 KB diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9b4fd09 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Shaw Walters and elizaOS Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 358fa1e..adeb7f2 100644 --- a/README.md +++ b/README.md @@ -1,230 +1,126 @@ -# @elizaos/plugin-tee +# TEE Core Plugin for Eliza -A plugin for handling Trusted Execution Environment (TEE) operations, providing secure key derivation and remote attestation capabilities. +The TEE Core Plugin for Eliza provides foundational capabilities for agents operating within a Trusted Execution Environment (TEE). It enables agents to perform remote attestation to prove their execution within a secure enclave and manage cryptographic keys securely. -## Overview +## Background -This plugin provides functionality to: +For Eliza agents running in a TEE, it's crucial to demonstrate this secure execution environment to external parties. Remote attestation allows an agent to generate a verifiable report, proving it's running genuine code within a specific TEE (like Intel TDX). This plugin provides the mechanisms for agents to leverage these TEE features, enhancing trust and security. Secure key derivation within the TEE is also essential for managing sensitive cryptographic operations. -- Generate secure keys within a TEE environment -- Derive Ed25519 keypairs for Solana -- Derive ECDSA keypairs for Ethereum -- Generate remote attestation quotes -- Manage wallet interactions with TEE-derived keys +## Requirements -## Installation - -```bash -npm install @elizaos/plugin-tee -``` - -## Configuration +- A TEE-enabled environment is required (e.g., Intel TDX) use [Phala Cloud](https://cloud.phala.network) for easy deployment. +- Configuration within Eliza to enable and utilize this plugin's features. The plugin requires the following environment variables: ```env +# For the environment you are running the TEE plugin. For local and container development, use `LOCAL` or `DOCKER`. For production deployments, use `PRODUCTION`. TEE_MODE=LOCAL|DOCKER|PRODUCTION -WALLET_SECRET_SALT=your_secret_salt # Required for single agent deployments -DSTACK_SIMULATOR_ENDPOINT=your-endpoint-url # Optional, for simulator purposes -``` - -## Usage - -Import and register the plugin in your Eliza configuration: - -```typescript -import { teePlugin } from "@elizaos/plugin-tee"; - -export default { - plugins: [teePlugin], - // ... other configuration -}; -``` +# Secret salt for your default agent to generate a key from through the derive key provider +WALLET_SECRET_SALT=your_secret_salt +# TEE_VENDOR only supports Phala at this time, but adding a vendor is easy and can be done to support more TEE Vendors in the TEE Plugin +TEE_VENDOR=phala ## Features -### DeriveKeyProvider - -The `DeriveKeyProvider` allows for secure key derivation within a TEE environment: - -```typescript -import { DeriveKeyProvider } from "@elizaos/plugin-tee"; - -// Initialize the provider -const provider = new DeriveKeyProvider(); - -// Derive a raw key -const rawKey = await provider.rawDeriveKey( - "/path/to/derive", - "subject-identifier" -); -// rawKey is a DeriveKeyResponse that can be used for further processing -const rawKeyArray = rawKey.asUint8Array(); - -// Derive a Solana keypair (Ed25519) -const solanaKeypair = await provider.deriveEd25519Keypair( - "/path/to/derive", - "subject-identifier" -); - -// Derive an Ethereum keypair (ECDSA) -const evmKeypair = await provider.deriveEcdsaKeypair( - "/path/to/derive", - "subject-identifier" -); -``` - -### RemoteAttestationProvider - -The `RemoteAttestationProvider` generates remote attestations within a TEE environment: +This plugin offers the following core TEE functionalities: -```typescript -import { RemoteAttestationProvider } from "@elizaos/plugin-tee"; - -const provider = new RemoteAttestationProvider(); -const attestation = await provider.generateAttestation("your-report-data"); -``` +1. **Remote Attestation**: -## Development - -### Building - -```bash -npm run build -``` - -### Testing - -```bash -npm run test -``` + - Provides actions and providers (`remoteAttestationAction`, `remoteAttestationProvider`) allowing agents to request and receive remote attestation reports. + - These reports can be presented to third parties to verify the agent's TEE residency. + - Includes support for specific TEE vendors/attestation services (e.g., Phala Network). -## Local Development +2. **Key Derivation**: + - Offers a `deriveKeyProvider` for securely deriving cryptographic keys within the TEE. + - Ensures that key material is generated and managed within the protected enclave memory. -To get a TEE simulator for local testing, use the following commands: +## Components -```bash -docker pull phalanetwork/tappd-simulator:latest -# by default the simulator is available in localhost:8090 -docker run --rm -p 8090:8090 phalanetwork/tappd-simulator:latest -``` +Based on the source code (`src/`): -## Dependencies +- **Actions**: + - `remoteAttestationAction.ts`: Likely handles agent requests to initiate the remote attestation process. +- **Providers**: + - `remoteAttestationProvider.ts`: Implements the logic for interacting with the underlying TEE platform or attestation service (like Phala) to generate the attestation report. + - `deriveKeyProvider.ts`: Implements the logic for TEE-specific key derivation. +- **Vendors**: + - `vendors/phala.ts`: Contains specific implementation details for interacting with the Phala Network's attestation services. + - `vendors/index.ts`, `vendors/types.ts`: Support vendor integration. +- **Utilities & Types**: + - `utils.ts`, `types.ts`: Contain helper functions and type definitions for the plugin. +- **Tests**: + - `__tests__/`: Includes unit tests for key derivation, remote attestation, etc. -- `@phala/dstack-sdk`: Core TEE functionality -- `@solana/web3.js`: Solana blockchain interaction -- `viem`: Ethereum interaction library -- Other standard dependencies listed in package.json +## Usage -## API Reference +_(This section may need further refinement based on how the plugin is integrated into the core Eliza system)_ -### Providers +To utilize the features of this plugin: -- `deriveKeyProvider`: Manages secure key derivation within TEE -- `remoteAttestationProvider`: Handles generation of remote attestation quotes -- `walletProvider`: Manages wallet interactions with TEE-derived keys +1. **Ensure the plugin is enabled** in your Eliza agent's configuration. +2. **Configure the TEE vendor** (e.g., specify 'phala' if using Phala Network attestation) if required by the environment setup. +3. **Call the relevant actions or services** provided by this plugin from other agent logic or plugins when remote attestation or secure key derivation is needed. -### Types +Example (Conceptual): ```typescript -enum TEEMode { - OFF = "OFF", - LOCAL = "LOCAL", // For local development with simulator - DOCKER = "DOCKER", // For docker development with simulator - PRODUCTION = "PRODUCTION", // For production without simulator +import import { PhalaDeriveKeyProvider, PhalaRemoteAttestationProvider } from '@elizaos/tee-plugin'; +// Assuming access to the runtime and its services/actions + +// Requesting remote attestation +async function getAttestation( + runtime: IAgentRuntime, + userData: string +): Promise { + try { + const provider = new PhalaRemoteAttestationProvider(teeMode); + + const attestation = await provider.generateAttestation(userData); + const attestationData = hexToUint8Array(attestation.quote); + const raQuote = await uploadUint8Array(attestationData); + return attestation; + } catch (error) { + console.error('Failed to get remote attestation:', error); + return null; + } } -interface RemoteAttestationQuote { - quote: string; - timestamp: number; +// Deriving a key +async function deriveAgentKeys( + runtime: IAgentRuntime, salt: string + ): Promise { + try { + // Potentially using a service/provider interface + const provider = new PhalaDeriveKeyProvider(teeMode) + const secretSalt = runtime.getSetting('WALLET_SECRET_SALT') || 'secret_salt'; + const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, 'solana', agentId); + const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, 'evm', agentId); + + // Original data structure + const walletData = { + solana: solanaKeypair.keypair.publicKey, + evm: evmKeypair.keypair.address, + }; + + // Values for template injection + const values = { + solana_public_key: solanaKeypair.keypair.publicKey.toString(), + evm_address: evmKeypair.keypair.address, + }; + + // Text representation + const text = `Solana Public Key: ${values.solana_public_key}\nEVM Address: ${values.evm_address}`; + + return { + data: walletData, + values: values, + text: text, + }; + return key; + } catch (error) { + console.error('Failed to derive key:', error); + return null; + } } ``` - -## Future Enhancements - -1. **Key Management** - - - Advanced key derivation schemes - - Multi-party computation support - - Key rotation automation - - Backup and recovery systems - - Hardware security module integration - - Custom derivation paths - -2. **Remote Attestation** - - - Enhanced quote verification - - Multiple TEE provider support - - Automated attestation renewal - - Policy management system - - Compliance reporting - - Audit trail generation - -3. **Security Features** - - - Memory encryption improvements - - Side-channel protection - - Secure state management - - Access control systems - - Threat detection - - Security monitoring - -4. **Chain Integration** - - - Multi-chain support expansion - - Cross-chain attestation - - Chain-specific optimizations - - Custom signing schemes - - Transaction privacy - - Bridge security - -5. **Developer Tools** - - - Enhanced debugging capabilities - - Testing framework - - Simulation environment - - Documentation generator - - Performance profiling - - Integration templates - -6. **Performance Optimization** - - Parallel processing - - Caching mechanisms - - Resource management - - Latency reduction - - Throughput improvements - - Load balancing - -We welcome community feedback and contributions to help prioritize these enhancements. - -## Contributing - -Contributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information. - -## Credits - -This plugin integrates with and builds upon several key technologies: - -- [Phala Network](https://phala.network/): Confidential smart contract platform -- [@phala/dstack-sdk](https://www.npmjs.com/package/@phala/dstack-sdk): Core TEE functionality -- [@solana/web3.js](https://www.npmjs.com/package/@solana/web3.js): Solana blockchain interaction -- [viem](https://www.npmjs.com/package/viem): Ethereum interaction library -- [Intel SGX](https://www.intel.com/content/www/us/en/developer/tools/software-guard-extensions/overview.html): Trusted Execution Environment technology - -Special thanks to: - -- The Phala Network team for their TEE infrastructure -- The Intel SGX team for TEE technology -- The dStack SDK maintainers -- The Eliza community for their contributions and feedback - -For more information about TEE capabilities: - -- [Phala Documentation](https://docs.phala.network/) -- [Intel SGX Documentation](https://www.intel.com/content/www/us/en/developer/tools/software-guard-extensions/documentation.html) -- [TEE Security Best Practices](https://docs.phala.network/developers/phat-contract/security-notes) -- [dStack SDK Reference](https://docs.phala.network/developers/dstack-sdk) - -## License - -This plugin is part of the Eliza project. See the main project repository for license information. diff --git a/__tests__/deriveKey.test.ts b/__tests__/deriveKey.test.ts deleted file mode 100644 index deabae7..0000000 --- a/__tests__/deriveKey.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { DeriveKeyProvider } from '../src/providers/deriveKeyProvider'; -import { TappdClient } from '@phala/dstack-sdk'; -import { TEEMode } from '../src/types/tee'; - -// Mock dependencies -vi.mock('@phala/dstack-sdk', () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - deriveKey: vi.fn().mockResolvedValue({ - asUint8Array: () => new Uint8Array([1, 2, 3, 4, 5]) - }), - tdxQuote: vi.fn().mockResolvedValue({ - quote: 'mock-quote-data', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] - }), - rawDeriveKey: vi.fn() - })) -})); - -vi.mock('@solana/web3.js', () => ({ - Keypair: { - fromSeed: vi.fn().mockReturnValue({ - publicKey: { - toBase58: () => 'mock-solana-public-key' - } - }) - } -})); - -vi.mock('viem/accounts', () => ({ - privateKeyToAccount: vi.fn().mockReturnValue({ - address: 'mock-evm-address' - }) -})); - -describe('DeriveKeyProvider', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - describe('constructor', () => { - it('should initialize with LOCAL mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); - }); - - it('should initialize with DOCKER mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); - }); - - it('should initialize with PRODUCTION mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.PRODUCTION); - expect(TappdClient).toHaveBeenCalledWith(); - }); - - it('should throw error for invalid mode', () => { - expect(() => new DeriveKeyProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); - }); - }); - - describe('rawDeriveKey', () => { - let _provider: DeriveKeyProvider; - - beforeEach(() => { - _provider = new DeriveKeyProvider(TEEMode.LOCAL); - }); - - it('should derive raw key successfully', async () => { - const path = 'test-path'; - const subject = 'test-subject'; - const result = await _provider.rawDeriveKey(path, subject); - - const client = TappdClient.mock.results[0].value; - expect(client.deriveKey).toHaveBeenCalledWith(path, subject); - expect(result.asUint8Array()).toEqual(new Uint8Array([1, 2, 3, 4, 5])); - }); - - it('should handle errors during raw key derivation', async () => { - const mockError = new Error('Key derivation failed'); - vi.mocked(TappdClient).mockImplementationOnce(() => { - const instance = new TappdClient(); - instance.deriveKey = vi.fn().mockRejectedValueOnce(mockError); - instance.tdxQuote = vi.fn(); - instance.rawDeriveKey = vi.fn(); - return instance; - }); - - const provider = new DeriveKeyProvider(TEEMode.LOCAL); - await expect(provider.rawDeriveKey('path', 'subject')).rejects.toThrow(mockError); - }); - }); - - describe('deriveEd25519Keypair', () => { - let provider: DeriveKeyProvider; - - beforeEach(() => { - provider = new DeriveKeyProvider(TEEMode.LOCAL); - }); - - it('should derive Ed25519 keypair successfully', async () => { - const path = 'test-path'; - const subject = 'test-subject'; - const result = await provider.deriveEd25519Keypair(path, subject); - - const client = TappdClient.mock.results[0].value; - expect(client.deriveKey).toHaveBeenCalledWith(path, subject); - expect(result.keypair.publicKey.toBase58()).toEqual('mock-solana-public-key'); - }); - }); -}); \ No newline at end of file diff --git a/__tests__/remoteAttestation.test.ts b/__tests__/remoteAttestation.test.ts deleted file mode 100644 index 4890d66..0000000 --- a/__tests__/remoteAttestation.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; -import { TappdClient } from '@phala/dstack-sdk'; -import { TEEMode } from '../src/types/tee'; - -// Mock TappdClient -vi.mock('@phala/dstack-sdk', () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - tdxQuote: vi.fn().mockResolvedValue({ - quote: 'mock-quote-data', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] - }), - deriveKey: vi.fn() - })) -})); - -describe('RemoteAttestationProvider', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - describe('constructor', () => { - it('should initialize with LOCAL mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); - }); - - it('should initialize with DOCKER mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); - }); - - it('should initialize with PRODUCTION mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.PRODUCTION); - expect(TappdClient).toHaveBeenCalledWith(); - }); - - it('should throw error for invalid mode', () => { - expect(() => new RemoteAttestationProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); - }); - }); - - describe('generateAttestation', () => { - let provider: RemoteAttestationProvider; - - beforeEach(() => { - provider = new RemoteAttestationProvider(TEEMode.LOCAL); - }); - - it('should generate attestation successfully', async () => { - const reportData = 'test-report-data'; - const quote = await provider.generateAttestation(reportData); - - expect(quote).toEqual({ - quote: 'mock-quote-data', - timestamp: expect.any(Number) - }); - }); - - it('should handle errors during attestation generation', async () => { - const mockError = new Error('TDX Quote generation failed'); - const mockTdxQuote = vi.fn().mockRejectedValue(mockError); - vi.mocked(TappdClient).mockImplementationOnce(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn() - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(provider.generateAttestation('test-data')).rejects.toThrow('Failed to generate TDX Quote'); - }); - - it('should pass hash algorithm to tdxQuote when provided', async () => { - const reportData = 'test-report-data'; - const hashAlgorithm = 'raw'; - await provider.generateAttestation(reportData, hashAlgorithm); - - const client = TappdClient.mock.results[0].value; - expect(client.tdxQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); - }); - }); -}); \ No newline at end of file diff --git a/__tests__/remoteAttestationAction.test.ts b/__tests__/remoteAttestationAction.test.ts deleted file mode 100644 index 897de2c..0000000 --- a/__tests__/remoteAttestationAction.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { remoteAttestationAction } from '../src/actions/remoteAttestation'; -import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; - -// Mock dependencies -vi.mock('../src/providers/remoteAttestationProvider'); -vi.mock('undici', () => ({ - fetch: vi.fn().mockResolvedValue({ - json: () => Promise.resolve({ checksum: 'mock-checksum' }) - }) -})); - -describe('remoteAttestationAction', () => { - const mockRuntime = { - agentId: 'test-agent-id', - getSetting: vi.fn().mockReturnValue('LOCAL'), - getState: vi.fn(), - setState: vi.fn(), - message:{ userId: 'user', roomId: 'room', content: { text: 'If you are running in a TEE, generate a remote attestation' } }, - setConversation: vi.fn() - }; - - const mockCallback = vi.fn(); - - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(RemoteAttestationProvider).mockImplementation(() => ({ - generateAttestation: vi.fn().mockResolvedValue({ - quote: '0x1234', - timestamp: Date.now() - }) - })); - }); - - it('should have correct name and similes', () => { - expect(remoteAttestationAction.name).toBe('REMOTE_ATTESTATION'); - expect(remoteAttestationAction.similes).toContain('REMOTE_ATTESTATION'); - expect(remoteAttestationAction.similes).toContain('TEE_REMOTE_ATTESTATION'); - expect(remoteAttestationAction.similes).toContain('TEE_ATTESTATION'); - }); - - describe('handler', () => { - it('should generate and upload attestation successfully', async () => { - const result = await remoteAttestationAction.handler( - mockRuntime, - mockRuntime.message, - {}, - {}, - mockCallback - ); - - expect(result).toBe(true); - expect(mockCallback).toHaveBeenCalledWith({ - text: expect.stringContaining('https://proof.t16z.com/reports/mock-checksum'), - action: 'NONE' - }); - }); - - it('should handle errors during attestation generation', async () => { - const mockError = new Error('Attestation generation failed'); - vi.mocked(RemoteAttestationProvider).mockImplementation(() => ({ - generateAttestation: vi.fn().mockRejectedValueOnce(mockError), - client: { - tdxQuote: vi.fn(), - deriveKey: vi.fn() - } - })); - - const result = await remoteAttestationAction.handler( - mockRuntime, - {}, - {}, - {}, - mockCallback - ); - - expect(result).toBe(false); - }); - }); - - describe('validate', () => { - it('should always return true', async () => { - const result = await remoteAttestationAction.validate(mockRuntime); - expect(result).toBe(true); - }); - }); - - describe('examples', () => { - it('should have valid example conversations', () => { - expect(remoteAttestationAction.examples).toBeInstanceOf(Array); - expect(remoteAttestationAction.examples[0]).toBeInstanceOf(Array); - - const [userMessage, agentMessage] = remoteAttestationAction.examples[0]; - expect(userMessage.user).toBe('{{user1}}'); - expect(userMessage.content.text).toBe('If you are running in a TEE, generate a remote attestation'); - expect(userMessage.content.action).toBe('REMOTE_ATTESTATION'); - - expect(agentMessage.user).toBe('{{user2}}'); - expect(agentMessage.content.text).toBe('Of course, one second...'); - expect(agentMessage.content.action).toBeUndefined(); - }); - }); -}); \ No newline at end of file diff --git a/__tests__/timeout.test.ts b/__tests__/timeout.test.ts deleted file mode 100644 index f16a54d..0000000 --- a/__tests__/timeout.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { RemoteAttestationProvider } from '../src/providers/remoteAttestationProvider'; -import { DeriveKeyProvider } from '../src/providers/deriveKeyProvider'; -import { TEEMode } from '../src/types/tee'; -import { TappdClient } from '@phala/dstack-sdk'; - -// Mock TappdClient -vi.mock('@phala/dstack-sdk', () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: vi.fn() - })) -})); - -describe('TEE Provider Timeout Tests', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - describe('RemoteAttestationProvider', () => { - it('should handle API timeout during attestation generation', async () => { - const mockTdxQuote = vi.fn() - .mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn() - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(() => provider.generateAttestation('test-data')) - .rejects - .toThrow('Failed to generate TDX Quote: Request timed out'); - - // Verify the call was made once - expect(mockTdxQuote).toHaveBeenCalledTimes(1); - expect(mockTdxQuote).toHaveBeenCalledWith('test-data', undefined); - }); - - it('should handle network errors during attestation generation', async () => { - const mockTdxQuote = vi.fn() - .mockRejectedValueOnce(new Error('Network error')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn() - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(() => provider.generateAttestation('test-data')) - .rejects - .toThrow('Failed to generate TDX Quote: Network error'); - - expect(mockTdxQuote).toHaveBeenCalledTimes(1); - }); - - it('should handle successful attestation generation', async () => { - const mockQuote = { - quote: 'test-quote', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'] - }; - - const mockTdxQuote = vi.fn().mockResolvedValueOnce(mockQuote); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn() - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - const result = await provider.generateAttestation('test-data'); - - expect(mockTdxQuote).toHaveBeenCalledTimes(1); - expect(result).toEqual({ - quote: 'test-quote', - timestamp: expect.any(Number) - }); - }); - }); - - describe('DeriveKeyProvider', () => { - it('should handle API timeout during key derivation', async () => { - const mockDeriveKey = vi.fn() - .mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: mockDeriveKey - })); - - const provider = new DeriveKeyProvider(TEEMode.LOCAL); - await expect(() => provider.rawDeriveKey('test-path', 'test-subject')) - .rejects - .toThrow('Request timed out'); - - expect(mockDeriveKey).toHaveBeenCalledTimes(1); - expect(mockDeriveKey).toHaveBeenCalledWith('test-path', 'test-subject'); - }); - - it('should handle API timeout during Ed25519 key derivation', async () => { - const mockDeriveKey = vi.fn() - .mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: mockDeriveKey - })); - - const provider = new DeriveKeyProvider(TEEMode.LOCAL); - await expect(() => provider.deriveEd25519Keypair('test-path', 'test-subject')) - .rejects - .toThrow('Request timed out'); - - expect(mockDeriveKey).toHaveBeenCalledTimes(1); - }); - }); -}); diff --git a/biome.json b/biome.json deleted file mode 100644 index 818716a..0000000 --- a/biome.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "$schema": "https://biomejs.dev/schemas/1.5.3/schema.json", - "organizeImports": { - "enabled": false - }, - "linter": { - "enabled": true, - "rules": { - "recommended": true, - "correctness": { - "noUnusedVariables": "error" - }, - "suspicious": { - "noExplicitAny": "error" - }, - "style": { - "useConst": "error", - "useImportType": "off" - } - } - }, - "formatter": { - "enabled": true, - "indentStyle": "space", - "indentWidth": 4, - "lineWidth": 100 - }, - "javascript": { - "formatter": { - "quoteStyle": "single", - "trailingCommas": "es5" - } - }, - "files": { - "ignore": [ - "dist/**/*", - "extra/**/*", - "node_modules/**/*" - ] - } -} \ No newline at end of file diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..d28065ecd38341e67f05c4fc7a1b3e999bfc9269 GIT binary patch literal 164895 zcmeFac|4U}7w~@+Atf4AqB3WmWr)l)%20+P(=lbrkVK_HqB0Z}ku$%_i&cXZ7@ArB3=f147_g>$%)*i2YUFY;XVj_y6!9j|y-u{Yo z|5ejnL;Xj>CGQ*Hw!*{PmoD!S5aj0)BEL#$Ei-kx|TiMmkfWFF%e(i(2JP_ruIpxJE-h zhbgl_j>38XctEBw^DeI5A>n~^ns;zOSTL0J{Q()U8va0f4}qYazuT*Yaseo}0i7`* z)7fdX2_R#b(lyk>gC0bqdDH3ind)k^4IDHYH`IqiJuk?8z@t1gf+3S2KN9j*kjFSf zf_=SR!L}LXF`%wP%kvp+Z~E%E0}g|KneBzurZJvndOT>Vmn}f+`auh zgExRPKFFIuIqK_xME};1L7572EXa@`H4U`m;}RYm;Qv?uTma|D$%0Xg;~@OO{!amk ze(2%!z6iE5^Wo4~)OV-*x`czh^-zxO`Fp#(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!ZK@!+?@;i_y3bX`;P*A&v4T!Pl&NPhts>>X(9cr05vXGmJ~kmiOhsUbVvN- zm2A*PJvsMjVwq~?E`Sj30IJfLJy{RV%@)|l1T?|?b^KNMcyk{tR;!HB0sb~5^zBAH zzLesK1|C0Oj)HH0#Hnpq>Gi-NCdaJk4r1eZ*6^5E8%`+|FA>w(kR>`PHP{erL$+`$ zA(`kAVNS0g=?*X9%BEGJfDVerWuen!cZ15Pj=%?voE5^THL2sigYKZ1TqXv6ANqJy zfIq$H(21o?e$}hQJD~FQ8gEytTPn1d}PMdB^Spz!U$Wm#9vDF3o}2ky#APpPvC zL6S)k?P8UjBCR!R^ z$_xT5*Fc!%n9Ye?*+N{+Bt0xko3wPmjo)bq&VTh;Mgjf`$l#AK9ip$Avr)J}RB7Xt z1{&4{TT;Z4wxcu$SJD7Y;FfxfZKCu#tCnWDP)LOQNmg67PhT~&x%OZsv z+y9tttXi%`k}$$ei7XZwERxt+ipnMg9*Za;Aw|;o;ARoVpQlI`-(ES>rJ%iXjDlxN z&Qhce<%a+X3lLa78v?ED91i4$F@B%Y*9ilC6RyZu2)!kCe3v68bC z$`Mo&B&Ebg5?&Zda`vM-38Na4A{>9842@hz#p;u9IkHRsw4DKT2uzH@rM{M z^Y18;>Fww_Z`^jJ``f}H_-OBf{QX6|x{R{IGxz~m1jeR8`OB^EmV?te0mEee#tS{+ vpfsCY4{oK`L7o*K8Cu){$v!Kn)fm0xUxp=I24TV>EKiSYp=gT#(7*o&)xYu4 literal 0 HcmV?d00001 diff --git a/dist/_esm-L4OBJJWB.js b/dist/_esm-L4OBJJWB.js deleted file mode 100644 index b53bc10..0000000 --- a/dist/_esm-L4OBJJWB.js +++ /dev/null @@ -1,3913 +0,0 @@ -import { - __commonJS, - __export, - __require, - __toESM -} from "./chunk-PR4QN5HX.js"; - -// ../../node_modules/ws/lib/stream.js -var require_stream = __commonJS({ - "../../node_modules/ws/lib/stream.js"(exports, module) { - "use strict"; - var { Duplex } = __require("stream"); - function emitClose(stream) { - stream.emit("close"); - } - function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } - } - function duplexOnError(err) { - this.removeListener("error", duplexOnError); - this.destroy(); - if (this.listenerCount("error") === 0) { - this.emit("error", err); - } - } - function createWebSocketStream2(ws, options) { - let terminateOnDestroy = true; - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - ws.on("message", function message(msg, isBinary) { - const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; - if (!duplex.push(data)) ws.pause(); - }); - ws.once("error", function error(err) { - if (duplex.destroyed) return; - terminateOnDestroy = false; - duplex.destroy(err); - }); - ws.once("close", function close() { - if (duplex.destroyed) return; - duplex.push(null); - }); - duplex._destroy = function(err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose, duplex); - return; - } - let called = false; - ws.once("error", function error(err2) { - called = true; - callback(err2); - }); - ws.once("close", function close() { - if (!called) callback(err); - process.nextTick(emitClose, duplex); - }); - if (terminateOnDestroy) ws.terminate(); - }; - duplex._final = function(callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open() { - duplex._final(callback); - }); - return; - } - if (ws._socket === null) return; - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) duplex.destroy(); - } else { - ws._socket.once("finish", function finish() { - callback(); - }); - ws.close(); - } - }; - duplex._read = function() { - if (ws.isPaused) ws.resume(); - }; - duplex._write = function(chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open() { - duplex._write(chunk, encoding, callback); - }); - return; - } - ws.send(chunk, callback); - }; - duplex.on("end", duplexOnEnd); - duplex.on("error", duplexOnError); - return duplex; - } - module.exports = createWebSocketStream2; - } -}); - -// ../../node_modules/ws/lib/constants.js -var require_constants = __commonJS({ - "../../node_modules/ws/lib/constants.js"(exports, module) { - "use strict"; - var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; - var hasBlob = typeof Blob !== "undefined"; - if (hasBlob) BINARY_TYPES.push("blob"); - module.exports = { - BINARY_TYPES, - EMPTY_BUFFER: Buffer.alloc(0), - GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", - hasBlob, - kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), - kListener: Symbol("kListener"), - kStatusCode: Symbol("status-code"), - kWebSocket: Symbol("websocket"), - NOOP: () => { - } - }; - } -}); - -// ../../node_modules/node-gyp-build/node-gyp-build.js -var require_node_gyp_build = __commonJS({ - "../../node_modules/node-gyp-build/node-gyp-build.js"(exports, module) { - var fs = __require("fs"); - var path = __require("path"); - var os = __require("os"); - var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; - var vars = process.config && process.config.variables || {}; - var prebuildsOnly = !!process.env.PREBUILDS_ONLY; - var abi = process.versions.modules; - var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; - var arch = process.env.npm_config_arch || os.arch(); - var platform = process.env.npm_config_platform || os.platform(); - var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc"); - var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; - var uv = (process.versions.uv || "").split(".")[0]; - module.exports = load; - function load(dir) { - return runtimeRequire(load.resolve(dir)); - } - load.resolve = load.path = function(dir) { - dir = path.resolve(dir || "."); - try { - var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_"); - if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"]; - } catch (err) { - } - if (!prebuildsOnly) { - var release = getFirst(path.join(dir, "build/Release"), matchBuild); - if (release) return release; - var debug = getFirst(path.join(dir, "build/Debug"), matchBuild); - if (debug) return debug; - } - var prebuild = resolve(dir); - if (prebuild) return prebuild; - var nearby = resolve(path.dirname(process.execPath)); - if (nearby) return nearby; - var target = [ - "platform=" + platform, - "arch=" + arch, - "runtime=" + runtime, - "abi=" + abi, - "uv=" + uv, - armv ? "armv=" + armv : "", - "libc=" + libc, - "node=" + process.versions.node, - process.versions.electron ? "electron=" + process.versions.electron : "", - typeof __webpack_require__ === "function" ? "webpack=true" : "" - // eslint-disable-line - ].filter(Boolean).join(" "); - throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n"); - function resolve(dir2) { - var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple); - var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]; - if (!tuple) return; - var prebuilds = path.join(dir2, "prebuilds", tuple.name); - var parsed = readdirSync(prebuilds).map(parseTags); - var candidates = parsed.filter(matchTags(runtime, abi)); - var winner = candidates.sort(compareTags(runtime))[0]; - if (winner) return path.join(prebuilds, winner.file); - } - }; - function readdirSync(dir) { - try { - return fs.readdirSync(dir); - } catch (err) { - return []; - } - } - function getFirst(dir, filter) { - var files = readdirSync(dir).filter(filter); - return files[0] && path.join(dir, files[0]); - } - function matchBuild(name) { - return /\.node$/.test(name); - } - function parseTuple(name) { - var arr = name.split("-"); - if (arr.length !== 2) return; - var platform2 = arr[0]; - var architectures = arr[1].split("+"); - if (!platform2) return; - if (!architectures.length) return; - if (!architectures.every(Boolean)) return; - return { name, platform: platform2, architectures }; - } - function matchTuple(platform2, arch2) { - return function(tuple) { - if (tuple == null) return false; - if (tuple.platform !== platform2) return false; - return tuple.architectures.includes(arch2); - }; - } - function compareTuples(a, b) { - return a.architectures.length - b.architectures.length; - } - function parseTags(file) { - var arr = file.split("."); - var extension = arr.pop(); - var tags = { file, specificity: 0 }; - if (extension !== "node") return; - for (var i = 0; i < arr.length; i++) { - var tag = arr[i]; - if (tag === "node" || tag === "electron" || tag === "node-webkit") { - tags.runtime = tag; - } else if (tag === "napi") { - tags.napi = true; - } else if (tag.slice(0, 3) === "abi") { - tags.abi = tag.slice(3); - } else if (tag.slice(0, 2) === "uv") { - tags.uv = tag.slice(2); - } else if (tag.slice(0, 4) === "armv") { - tags.armv = tag.slice(4); - } else if (tag === "glibc" || tag === "musl") { - tags.libc = tag; - } else { - continue; - } - tags.specificity++; - } - return tags; - } - function matchTags(runtime2, abi2) { - return function(tags) { - if (tags == null) return false; - if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false; - if (tags.abi && tags.abi !== abi2 && !tags.napi) return false; - if (tags.uv && tags.uv !== uv) return false; - if (tags.armv && tags.armv !== armv) return false; - if (tags.libc && tags.libc !== libc) return false; - return true; - }; - } - function runtimeAgnostic(tags) { - return tags.runtime === "node" && tags.napi; - } - function compareTags(runtime2) { - return function(a, b) { - if (a.runtime !== b.runtime) { - return a.runtime === runtime2 ? -1 : 1; - } else if (a.abi !== b.abi) { - return a.abi ? -1 : 1; - } else if (a.specificity !== b.specificity) { - return a.specificity > b.specificity ? -1 : 1; - } else { - return 0; - } - }; - } - function isNwjs() { - return !!(process.versions && process.versions.nw); - } - function isElectron() { - if (process.versions && process.versions.electron) return true; - if (process.env.ELECTRON_RUN_AS_NODE) return true; - return typeof window !== "undefined" && window.process && window.process.type === "renderer"; - } - function isAlpine(platform2) { - return platform2 === "linux" && fs.existsSync("/etc/alpine-release"); - } - load.parseTags = parseTags; - load.matchTags = matchTags; - load.compareTags = compareTags; - load.parseTuple = parseTuple; - load.matchTuple = matchTuple; - load.compareTuples = compareTuples; - } -}); - -// ../../node_modules/node-gyp-build/index.js -var require_node_gyp_build2 = __commonJS({ - "../../node_modules/node-gyp-build/index.js"(exports, module) { - var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; - if (typeof runtimeRequire.addon === "function") { - module.exports = runtimeRequire.addon.bind(runtimeRequire); - } else { - module.exports = require_node_gyp_build(); - } - } -}); - -// ../../node_modules/bufferutil/fallback.js -var require_fallback = __commonJS({ - "../../node_modules/bufferutil/fallback.js"(exports, module) { - "use strict"; - var mask = (source, mask2, output, offset, length) => { - for (var i = 0; i < length; i++) { - output[offset + i] = source[i] ^ mask2[i & 3]; - } - }; - var unmask = (buffer, mask2) => { - const length = buffer.length; - for (var i = 0; i < length; i++) { - buffer[i] ^= mask2[i & 3]; - } - }; - module.exports = { mask, unmask }; - } -}); - -// ../../node_modules/bufferutil/index.js -var require_bufferutil = __commonJS({ - "../../node_modules/bufferutil/index.js"(exports, module) { - "use strict"; - try { - module.exports = require_node_gyp_build2()(__dirname); - } catch (e) { - module.exports = require_fallback(); - } - } -}); - -// ../../node_modules/ws/lib/buffer-util.js -var require_buffer_util = __commonJS({ - "../../node_modules/ws/lib/buffer-util.js"(exports, module) { - "use strict"; - var { EMPTY_BUFFER } = require_constants(); - var FastBuffer = Buffer[Symbol.species]; - function concat(list, totalLength) { - if (list.length === 0) return EMPTY_BUFFER; - if (list.length === 1) return list[0]; - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - for (let i = 0; i < list.length; i++) { - const buf = list[i]; - target.set(buf, offset); - offset += buf.length; - } - if (offset < totalLength) { - return new FastBuffer(target.buffer, target.byteOffset, offset); - } - return target; - } - function _mask(source, mask, output, offset, length) { - for (let i = 0; i < length; i++) { - output[offset + i] = source[i] ^ mask[i & 3]; - } - } - function _unmask(buffer, mask) { - for (let i = 0; i < buffer.length; i++) { - buffer[i] ^= mask[i & 3]; - } - } - function toArrayBuffer(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; - } - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); - } - function toBuffer(data) { - toBuffer.readOnly = true; - if (Buffer.isBuffer(data)) return data; - let buf; - if (data instanceof ArrayBuffer) { - buf = new FastBuffer(data); - } else if (ArrayBuffer.isView(data)) { - buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); - } else { - buf = Buffer.from(data); - toBuffer.readOnly = false; - } - return buf; - } - module.exports = { - concat, - mask: _mask, - toArrayBuffer, - toBuffer, - unmask: _unmask - }; - if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil = require_bufferutil(); - module.exports.mask = function(source, mask, output, offset, length) { - if (length < 48) _mask(source, mask, output, offset, length); - else bufferUtil.mask(source, mask, output, offset, length); - }; - module.exports.unmask = function(buffer, mask) { - if (buffer.length < 32) _unmask(buffer, mask); - else bufferUtil.unmask(buffer, mask); - }; - } catch (e) { - } - } - } -}); - -// ../../node_modules/ws/lib/limiter.js -var require_limiter = __commonJS({ - "../../node_modules/ws/lib/limiter.js"(exports, module) { - "use strict"; - var kDone = Symbol("kDone"); - var kRun = Symbol("kRun"); - var Limiter = class { - /** - * Creates a new `Limiter`. - * - * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed - * to run concurrently - */ - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; - } - /** - * Adds a job to the queue. - * - * @param {Function} job The job to run - * @public - */ - add(job) { - this.jobs.push(job); - this[kRun](); - } - /** - * Removes a job from the queue and runs it if possible. - * - * @private - */ - [kRun]() { - if (this.pending === this.concurrency) return; - if (this.jobs.length) { - const job = this.jobs.shift(); - this.pending++; - job(this[kDone]); - } - } - }; - module.exports = Limiter; - } -}); - -// ../../node_modules/ws/lib/permessage-deflate.js -var require_permessage_deflate = __commonJS({ - "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) { - "use strict"; - var zlib = __require("zlib"); - var bufferUtil = require_buffer_util(); - var Limiter = require_limiter(); - var { kStatusCode } = require_constants(); - var FastBuffer = Buffer[Symbol.species]; - var TRAILER = Buffer.from([0, 0, 255, 255]); - var kPerMessageDeflate = Symbol("permessage-deflate"); - var kTotalLength = Symbol("total-length"); - var kCallback = Symbol("callback"); - var kBuffers = Symbol("buffers"); - var kError = Symbol("error"); - var zlibLimiter; - var PerMessageDeflate = class { - /** - * Creates a PerMessageDeflate instance. - * - * @param {Object} [options] Configuration options - * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support - * for, or request, a custom client window size - * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ - * acknowledge disabling of client context takeover - * @param {Number} [options.concurrencyLimit=10] The number of concurrent - * calls to zlib - * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the - * use of a custom server window size - * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept - * disabling of server context takeover - * @param {Number} [options.threshold=1024] Size (in bytes) below which - * messages should not be compressed if context takeover is disabled - * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on - * deflate - * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on - * inflate - * @param {Boolean} [isServer=false] Create the instance in either server or - * client mode - * @param {Number} [maxPayload=0] The maximum allowed message length - */ - constructor(options, isServer, maxPayload) { - this._maxPayload = maxPayload | 0; - this._options = options || {}; - this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; - this._isServer = !!isServer; - this._deflate = null; - this._inflate = null; - this.params = null; - if (!zlibLimiter) { - const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; - zlibLimiter = new Limiter(concurrency); - } - } - /** - * @type {String} - */ - static get extensionName() { - return "permessage-deflate"; - } - /** - * Create an extension negotiation offer. - * - * @return {Object} Extension parameters - * @public - */ - offer() { - const params = {}; - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - return params; - } - /** - * Accept an extension negotiation offer/response. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Object} Accepted configuration - * @public - */ - accept(configurations) { - configurations = this.normalizeParams(configurations); - this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); - return this.params; - } - /** - * Releases all resources used by the extension. - * - * @public - */ - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - if (this._deflate) { - const callback = this._deflate[kCallback]; - this._deflate.close(); - this._deflate = null; - if (callback) { - callback( - new Error( - "The deflate stream was closed while data was being processed" - ) - ); - } - } - } - /** - * Accept an extension negotiation offer. - * - * @param {Array} offers The extension negotiation offers - * @return {Object} Accepted configuration - * @private - */ - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { - return false; - } - return true; - }); - if (!accepted) { - throw new Error("None of the extension offers can be accepted"); - } - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; - } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; - } - if (typeof opts.serverMaxWindowBits === "number") { - accepted.server_max_window_bits = opts.serverMaxWindowBits; - } - if (typeof opts.clientMaxWindowBits === "number") { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { - delete accepted.client_max_window_bits; - } - return accepted; - } - /** - * Accept the extension negotiation response. - * - * @param {Array} response The extension negotiation response - * @return {Object} Accepted configuration - * @private - */ - acceptAsClient(response) { - const params = response[0]; - if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === "number") { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { - throw new Error( - 'Unexpected or invalid parameter "client_max_window_bits"' - ); - } - return params; - } - /** - * Normalize parameters. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Array} The offers/response with normalized parameters - * @private - */ - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - value = value[0]; - if (key === "client_max_window_bits") { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (!this._isServer) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else if (key === "server_max_window_bits") { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { - if (value !== true) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - params[key] = value; - }); - }); - return configurations; - } - /** - * Decompress data. Concurrency limited. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - decompress(data, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - /** - * Compress data. Concurrency limited. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - compress(data, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - /** - * Decompress data. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _decompress(data, fin, callback) { - const endpoint = this._isServer ? "client" : "server"; - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on("error", inflateOnError); - this._inflate.on("data", inflateOnData); - } - this._inflate[kCallback] = callback; - this._inflate.write(data); - if (fin) this._inflate.write(TRAILER); - this._inflate.flush(() => { - const err = this._inflate[kError]; - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - const data2 = bufferUtil.concat( - this._inflate[kBuffers], - this._inflate[kTotalLength] - ); - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - callback(null, data2); - }); - } - /** - * Compress data. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _compress(data, fin, callback) { - const endpoint = this._isServer ? "server" : "client"; - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - this._deflate.on("data", deflateOnData); - } - this._deflate[kCallback] = callback; - this._deflate.write(data); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - return; - } - let data2 = bufferUtil.concat( - this._deflate[kBuffers], - this._deflate[kTotalLength] - ); - if (fin) { - data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); - } - this._deflate[kCallback] = null; - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - callback(null, data2); - }); - } - }; - module.exports = PerMessageDeflate; - function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; - } - function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { - this[kBuffers].push(chunk); - return; - } - this[kError] = new RangeError("Max payload size exceeded"); - this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; - this[kError][kStatusCode] = 1009; - this.removeListener("data", inflateOnData); - this.reset(); - } - function inflateOnError(err) { - this[kPerMessageDeflate]._inflate = null; - err[kStatusCode] = 1007; - this[kCallback](err); - } - } -}); - -// ../../node_modules/utf-8-validate/fallback.js -var require_fallback2 = __commonJS({ - "../../node_modules/utf-8-validate/fallback.js"(exports, module) { - "use strict"; - function isValidUTF8(buf) { - const len = buf.length; - let i = 0; - while (i < len) { - if ((buf[i] & 128) === 0) { - i++; - } else if ((buf[i] & 224) === 192) { - if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { - return false; - } - i += 2; - } else if ((buf[i] & 240) === 224) { - if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // overlong - buf[i] === 237 && (buf[i + 1] & 224) === 160) { - return false; - } - i += 3; - } else if ((buf[i] & 248) === 240) { - if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // overlong - buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { - return false; - } - i += 4; - } else { - return false; - } - } - return true; - } - module.exports = isValidUTF8; - } -}); - -// ../../node_modules/utf-8-validate/index.js -var require_utf_8_validate = __commonJS({ - "../../node_modules/utf-8-validate/index.js"(exports, module) { - "use strict"; - try { - module.exports = require_node_gyp_build2()(__dirname); - } catch (e) { - module.exports = require_fallback2(); - } - } -}); - -// ../../node_modules/ws/lib/validation.js -var require_validation = __commonJS({ - "../../node_modules/ws/lib/validation.js"(exports, module) { - "use strict"; - var { isUtf8 } = __require("buffer"); - var { hasBlob } = require_constants(); - var tokenChars = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - // 0 - 15 - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - // 16 - 31 - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - // 32 - 47 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - // 48 - 63 - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - // 64 - 79 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - // 80 - 95 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - // 96 - 111 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0 - // 112 - 127 - ]; - function isValidStatusCode(code) { - return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; - } - function _isValidUTF8(buf) { - const len = buf.length; - let i = 0; - while (i < len) { - if ((buf[i] & 128) === 0) { - i++; - } else if ((buf[i] & 224) === 192) { - if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { - return false; - } - i += 2; - } else if ((buf[i] & 240) === 224) { - if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong - buf[i] === 237 && (buf[i + 1] & 224) === 160) { - return false; - } - i += 3; - } else if ((buf[i] & 248) === 240) { - if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong - buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { - return false; - } - i += 4; - } else { - return false; - } - } - return true; - } - function isBlob(value) { - return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); - } - module.exports = { - isBlob, - isValidStatusCode, - isValidUTF8: _isValidUTF8, - tokenChars - }; - if (isUtf8) { - module.exports.isValidUTF8 = function(buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); - }; - } else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = require_utf_8_validate(); - module.exports.isValidUTF8 = function(buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); - }; - } catch (e) { - } - } - } -}); - -// ../../node_modules/ws/lib/receiver.js -var require_receiver = __commonJS({ - "../../node_modules/ws/lib/receiver.js"(exports, module) { - "use strict"; - var { Writable } = __require("stream"); - var PerMessageDeflate = require_permessage_deflate(); - var { - BINARY_TYPES, - EMPTY_BUFFER, - kStatusCode, - kWebSocket - } = require_constants(); - var { concat, toArrayBuffer, unmask } = require_buffer_util(); - var { isValidStatusCode, isValidUTF8 } = require_validation(); - var FastBuffer = Buffer[Symbol.species]; - var GET_INFO = 0; - var GET_PAYLOAD_LENGTH_16 = 1; - var GET_PAYLOAD_LENGTH_64 = 2; - var GET_MASK = 3; - var GET_DATA = 4; - var INFLATING = 5; - var DEFER_EVENT = 6; - var Receiver2 = class extends Writable { - /** - * Creates a Receiver instance. - * - * @param {Object} [options] Options object - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {String} [options.binaryType=nodebuffer] The type for binary data - * @param {Object} [options.extensions] An object containing the negotiated - * extensions - * @param {Boolean} [options.isServer=false] Specifies whether to operate in - * client or server mode - * @param {Number} [options.maxPayload=0] The maximum allowed message length - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - */ - constructor(options = {}) { - super(); - this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; - this._binaryType = options.binaryType || BINARY_TYPES[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket] = void 0; - this._bufferedBytes = 0; - this._buffers = []; - this._compressed = false; - this._payloadLength = 0; - this._mask = void 0; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - this._errored = false; - this._loop = false; - this._state = GET_INFO; - } - /** - * Implements `Writable.prototype._write()`. - * - * @param {Buffer} chunk The chunk of data to write - * @param {String} encoding The character encoding of `chunk` - * @param {Function} cb Callback - * @private - */ - _write(chunk, encoding, cb) { - if (this._opcode === 8 && this._state == GET_INFO) return cb(); - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); - } - /** - * Consumes `n` bytes from the buffered data. - * - * @param {Number} n The number of bytes to consume - * @return {Buffer} The consumed bytes - * @private - */ - consume(n) { - this._bufferedBytes -= n; - if (n === this._buffers[0].length) return this._buffers.shift(); - if (n < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - return new FastBuffer(buf.buffer, buf.byteOffset, n); - } - const dst = Buffer.allocUnsafe(n); - do { - const buf = this._buffers[0]; - const offset = dst.length - n; - if (n >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - } - n -= buf.length; - } while (n > 0); - return dst; - } - /** - * Starts the parsing loop. - * - * @param {Function} cb Callback - * @private - */ - startLoop(cb) { - this._loop = true; - do { - switch (this._state) { - case GET_INFO: - this.getInfo(cb); - break; - case GET_PAYLOAD_LENGTH_16: - this.getPayloadLength16(cb); - break; - case GET_PAYLOAD_LENGTH_64: - this.getPayloadLength64(cb); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - this.getData(cb); - break; - case INFLATING: - case DEFER_EVENT: - this._loop = false; - return; - } - } while (this._loop); - if (!this._errored) cb(); - } - /** - * Reads the first two bytes of a frame. - * - * @param {Function} cb Callback - * @private - */ - getInfo(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - const buf = this.consume(2); - if ((buf[0] & 48) !== 0) { - const error = this.createError( - RangeError, - "RSV2 and RSV3 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_2_3" - ); - cb(error); - return; - } - const compressed = (buf[0] & 64) === 64; - if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { - const error = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error); - return; - } - this._fin = (buf[0] & 128) === 128; - this._opcode = buf[0] & 15; - this._payloadLength = buf[1] & 127; - if (this._opcode === 0) { - if (compressed) { - const error = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error); - return; - } - if (!this._fragmented) { - const error = this.createError( - RangeError, - "invalid opcode 0", - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error); - return; - } - this._opcode = this._fragmented; - } else if (this._opcode === 1 || this._opcode === 2) { - if (this._fragmented) { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error); - return; - } - this._compressed = compressed; - } else if (this._opcode > 7 && this._opcode < 11) { - if (!this._fin) { - const error = this.createError( - RangeError, - "FIN must be set", - true, - 1002, - "WS_ERR_EXPECTED_FIN" - ); - cb(error); - return; - } - if (compressed) { - const error = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error); - return; - } - if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { - const error = this.createError( - RangeError, - `invalid payload length ${this._payloadLength}`, - true, - 1002, - "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" - ); - cb(error); - return; - } - } else { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error); - return; - } - if (!this._fin && !this._fragmented) this._fragmented = this._opcode; - this._masked = (buf[1] & 128) === 128; - if (this._isServer) { - if (!this._masked) { - const error = this.createError( - RangeError, - "MASK must be set", - true, - 1002, - "WS_ERR_EXPECTED_MASK" - ); - cb(error); - return; - } - } else if (this._masked) { - const error = this.createError( - RangeError, - "MASK must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_MASK" - ); - cb(error); - return; - } - if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; - else this.haveLength(cb); - } - /** - * Gets extended payload length (7+16). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength16(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - this._payloadLength = this.consume(2).readUInt16BE(0); - this.haveLength(cb); - } - /** - * Gets extended payload length (7+64). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength64(cb) { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - if (num > Math.pow(2, 53 - 32) - 1) { - const error = this.createError( - RangeError, - "Unsupported WebSocket frame: payload length > 2^53 - 1", - false, - 1009, - "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" - ); - cb(error); - return; - } - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - this.haveLength(cb); - } - /** - * Payload length has been read. - * - * @param {Function} cb Callback - * @private - */ - haveLength(cb) { - if (this._payloadLength && this._opcode < 8) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - "Max payload size exceeded", - false, - 1009, - "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" - ); - cb(error); - return; - } - } - if (this._masked) this._state = GET_MASK; - else this._state = GET_DATA; - } - /** - * Reads mask bytes. - * - * @private - */ - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - this._mask = this.consume(4); - this._state = GET_DATA; - } - /** - * Reads data bytes. - * - * @param {Function} cb Callback - * @private - */ - getData(cb) { - let data = EMPTY_BUFFER; - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - data = this.consume(this._payloadLength); - if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { - unmask(data, this._mask); - } - } - if (this._opcode > 7) { - this.controlMessage(data, cb); - return; - } - if (this._compressed) { - this._state = INFLATING; - this.decompress(data, cb); - return; - } - if (data.length) { - this._messageLength = this._totalPayloadLength; - this._fragments.push(data); - } - this.dataMessage(cb); - } - /** - * Decompresses data. - * - * @param {Buffer} data Compressed data - * @param {Function} cb Callback - * @private - */ - decompress(data, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - perMessageDeflate.decompress(data, this._fin, (err, buf) => { - if (err) return cb(err); - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - "Max payload size exceeded", - false, - 1009, - "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" - ); - cb(error); - return; - } - this._fragments.push(buf); - } - this.dataMessage(cb); - if (this._state === GET_INFO) this.startLoop(cb); - }); - } - /** - * Handles a data message. - * - * @param {Function} cb Callback - * @private - */ - dataMessage(cb) { - if (!this._fin) { - this._state = GET_INFO; - return; - } - const messageLength = this._messageLength; - const fragments = this._fragments; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - if (this._opcode === 2) { - let data; - if (this._binaryType === "nodebuffer") { - data = concat(fragments, messageLength); - } else if (this._binaryType === "arraybuffer") { - data = toArrayBuffer(concat(fragments, messageLength)); - } else if (this._binaryType === "blob") { - data = new Blob(fragments); - } else { - data = fragments; - } - if (this._allowSynchronousEvents) { - this.emit("message", data, true); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", data, true); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } else { - const buf = concat(fragments, messageLength); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - "invalid UTF-8 sequence", - true, - 1007, - "WS_ERR_INVALID_UTF8" - ); - cb(error); - return; - } - if (this._state === INFLATING || this._allowSynchronousEvents) { - this.emit("message", buf, false); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", buf, false); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - } - /** - * Handles a control message. - * - * @param {Buffer} data Data to handle - * @return {(Error|RangeError|undefined)} A possible error - * @private - */ - controlMessage(data, cb) { - if (this._opcode === 8) { - if (data.length === 0) { - this._loop = false; - this.emit("conclude", 1005, EMPTY_BUFFER); - this.end(); - } else { - const code = data.readUInt16BE(0); - if (!isValidStatusCode(code)) { - const error = this.createError( - RangeError, - `invalid status code ${code}`, - true, - 1002, - "WS_ERR_INVALID_CLOSE_CODE" - ); - cb(error); - return; - } - const buf = new FastBuffer( - data.buffer, - data.byteOffset + 2, - data.length - 2 - ); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - "invalid UTF-8 sequence", - true, - 1007, - "WS_ERR_INVALID_UTF8" - ); - cb(error); - return; - } - this._loop = false; - this.emit("conclude", code, buf); - this.end(); - } - this._state = GET_INFO; - return; - } - if (this._allowSynchronousEvents) { - this.emit(this._opcode === 9 ? "ping" : "pong", data); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit(this._opcode === 9 ? "ping" : "pong", data); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - /** - * Builds an error object. - * - * @param {function(new:Error|RangeError)} ErrorCtor The error constructor - * @param {String} message The error message - * @param {Boolean} prefix Specifies whether or not to add a default prefix to - * `message` - * @param {Number} statusCode The status code - * @param {String} errorCode The exposed error code - * @return {(Error|RangeError)} The error - * @private - */ - createError(ErrorCtor, message, prefix, statusCode, errorCode) { - this._loop = false; - this._errored = true; - const err = new ErrorCtor( - prefix ? `Invalid WebSocket frame: ${message}` : message - ); - Error.captureStackTrace(err, this.createError); - err.code = errorCode; - err[kStatusCode] = statusCode; - return err; - } - }; - module.exports = Receiver2; - } -}); - -// ../../node_modules/ws/lib/sender.js -var require_sender = __commonJS({ - "../../node_modules/ws/lib/sender.js"(exports, module) { - "use strict"; - var { Duplex } = __require("stream"); - var { randomFillSync } = __require("crypto"); - var PerMessageDeflate = require_permessage_deflate(); - var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants(); - var { isBlob, isValidStatusCode } = require_validation(); - var { mask: applyMask, toBuffer } = require_buffer_util(); - var kByteLength = Symbol("kByteLength"); - var maskBuffer = Buffer.alloc(4); - var RANDOM_POOL_SIZE = 8 * 1024; - var randomPool; - var randomPoolPointer = RANDOM_POOL_SIZE; - var DEFAULT = 0; - var DEFLATING = 1; - var GET_BLOB_DATA = 2; - var Sender2 = class _Sender { - /** - * Creates a Sender instance. - * - * @param {Duplex} socket The connection socket - * @param {Object} [extensions] An object containing the negotiated extensions - * @param {Function} [generateMask] The function used to generate the masking - * key - */ - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - this._socket = socket; - this._firstFragment = true; - this._compress = false; - this._bufferedBytes = 0; - this._queue = []; - this._state = DEFAULT; - this.onerror = NOOP; - this[kWebSocket] = void 0; - } - /** - * Frames a piece of data according to the HyBi WebSocket protocol. - * - * @param {(Buffer|String)} data The data to frame - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @return {(Buffer|String)[]} The framed data - * @public - */ - static frame(data, options) { - let mask; - let merge = false; - let offset = 2; - let skipMasking = false; - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - if (options.generateMask) { - options.generateMask(mask); - } else { - if (randomPoolPointer === RANDOM_POOL_SIZE) { - if (randomPool === void 0) { - randomPool = Buffer.alloc(RANDOM_POOL_SIZE); - } - randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); - randomPoolPointer = 0; - } - mask[0] = randomPool[randomPoolPointer++]; - mask[1] = randomPool[randomPoolPointer++]; - mask[2] = randomPool[randomPoolPointer++]; - mask[3] = randomPool[randomPoolPointer++]; - } - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - let dataLength; - if (typeof data === "string") { - if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { - dataLength = options[kByteLength]; - } else { - data = Buffer.from(data); - dataLength = data.length; - } - } else { - dataLength = data.length; - merge = options.mask && options.readOnly && !skipMasking; - } - let payloadLength = dataLength; - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); - target[0] = options.fin ? options.opcode | 128 : options.opcode; - if (options.rsv1) target[0] |= 64; - target[1] = payloadLength; - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - if (!options.mask) return [target, data]; - target[1] |= 128; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - if (skipMasking) return [target, data]; - if (merge) { - applyMask(data, mask, target, offset, dataLength); - return [target]; - } - applyMask(data, mask, data, 0, dataLength); - return [target, data]; - } - /** - * Sends a close message to the other peer. - * - * @param {Number} [code] The status code component of the body - * @param {(String|Buffer)} [data] The message component of the body - * @param {Boolean} [mask=false] Specifies whether or not to mask the message - * @param {Function} [cb] Callback - * @public - */ - close(code, data, mask, cb) { - let buf; - if (code === void 0) { - buf = EMPTY_BUFFER; - } else if (typeof code !== "number" || !isValidStatusCode(code)) { - throw new TypeError("First argument must be a valid error code number"); - } else if (data === void 0 || !data.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data); - if (length > 123) { - throw new RangeError("The message must not be greater than 123 bytes"); - } - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - if (typeof data === "string") { - buf.write(data, 2); - } else { - buf.set(data, 2); - } - } - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 8, - readOnly: false, - rsv1: false - }; - if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(buf, options), cb); - } - } - /** - * Sends a ping message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - ping(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 9, - readOnly, - rsv1: false - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(data, options), cb); - } - } - /** - * Sends a pong message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - pong(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 10, - readOnly, - rsv1: false - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(data, options), cb); - } - } - /** - * Sends a data message to the other peer. - * - * @param {*} data The message to send - * @param {Object} options Options object - * @param {Boolean} [options.binary=false] Specifies whether `data` is binary - * or text - * @param {Boolean} [options.compress=false] Specifies whether or not to - * compress `data` - * @param {Boolean} [options.fin=false] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Function} [cb] Callback - * @public - */ - send(data, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (this._firstFragment) { - this._firstFragment = false; - if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { - rsv1 = byteLength >= perMessageDeflate._threshold; - } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - if (options.fin) this._firstFragment = true; - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, this._compress, opts, cb]); - } else { - this.getBlobData(data, this._compress, opts, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, this._compress, opts, cb]); - } else { - this.dispatch(data, this._compress, opts, cb); - } - } - /** - * Gets the contents of a blob as binary data. - * - * @param {Blob} blob The blob - * @param {Boolean} [compress=false] Specifies whether or not to compress - * the data - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - getBlobData(blob, compress, options, cb) { - this._bufferedBytes += options[kByteLength]; - this._state = GET_BLOB_DATA; - blob.arrayBuffer().then((arrayBuffer) => { - if (this._socket.destroyed) { - const err = new Error( - "The socket was closed while the blob was being read" - ); - process.nextTick(callCallbacks, this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - const data = toBuffer(arrayBuffer); - if (!compress) { - this._state = DEFAULT; - this.sendFrame(_Sender.frame(data, options), cb); - this.dequeue(); - } else { - this.dispatch(data, compress, options, cb); - } - }).catch((err) => { - process.nextTick(onError, this, err, cb); - }); - } - /** - * Dispatches a message. - * - * @param {(Buffer|String)} data The message to send - * @param {Boolean} [compress=false] Specifies whether or not to compress - * `data` - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - dispatch(data, compress, options, cb) { - if (!compress) { - this.sendFrame(_Sender.frame(data, options), cb); - return; - } - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - this._bufferedBytes += options[kByteLength]; - this._state = DEFLATING; - perMessageDeflate.compress(data, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error( - "The socket was closed while data was being compressed" - ); - callCallbacks(this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - this._state = DEFAULT; - options.readOnly = false; - this.sendFrame(_Sender.frame(buf, options), cb); - this.dequeue(); - }); - } - /** - * Executes queued send operations. - * - * @private - */ - dequeue() { - while (this._state === DEFAULT && this._queue.length) { - const params = this._queue.shift(); - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - /** - * Enqueues a send operation. - * - * @param {Array} params Send operation parameters. - * @private - */ - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); - } - /** - * Sends a frame. - * - * @param {Buffer[]} list The frame to send - * @param {Function} [cb] Callback - * @private - */ - sendFrame(list, cb) { - if (list.length === 2) { - this._socket.cork(); - this._socket.write(list[0]); - this._socket.write(list[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list[0], cb); - } - } - }; - module.exports = Sender2; - function callCallbacks(sender, err, cb) { - if (typeof cb === "function") cb(err); - for (let i = 0; i < sender._queue.length; i++) { - const params = sender._queue[i]; - const callback = params[params.length - 1]; - if (typeof callback === "function") callback(err); - } - } - function onError(sender, err, cb) { - callCallbacks(sender, err, cb); - sender.onerror(err); - } - } -}); - -// ../../node_modules/ws/lib/event-target.js -var require_event_target = __commonJS({ - "../../node_modules/ws/lib/event-target.js"(exports, module) { - "use strict"; - var { kForOnEventAttribute, kListener } = require_constants(); - var kCode = Symbol("kCode"); - var kData = Symbol("kData"); - var kError = Symbol("kError"); - var kMessage = Symbol("kMessage"); - var kReason = Symbol("kReason"); - var kTarget = Symbol("kTarget"); - var kType = Symbol("kType"); - var kWasClean = Symbol("kWasClean"); - var Event = class { - /** - * Create a new `Event`. - * - * @param {String} type The name of the event - * @throws {TypeError} If the `type` argument is not specified - */ - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - /** - * @type {*} - */ - get target() { - return this[kTarget]; - } - /** - * @type {String} - */ - get type() { - return this[kType]; - } - }; - Object.defineProperty(Event.prototype, "target", { enumerable: true }); - Object.defineProperty(Event.prototype, "type", { enumerable: true }); - var CloseEvent = class extends Event { - /** - * Create a new `CloseEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {Number} [options.code=0] The status code explaining why the - * connection was closed - * @param {String} [options.reason=''] A human-readable string explaining why - * the connection was closed - * @param {Boolean} [options.wasClean=false] Indicates whether or not the - * connection was cleanly closed - */ - constructor(type, options = {}) { - super(type); - this[kCode] = options.code === void 0 ? 0 : options.code; - this[kReason] = options.reason === void 0 ? "" : options.reason; - this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; - } - /** - * @type {Number} - */ - get code() { - return this[kCode]; - } - /** - * @type {String} - */ - get reason() { - return this[kReason]; - } - /** - * @type {Boolean} - */ - get wasClean() { - return this[kWasClean]; - } - }; - Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); - var ErrorEvent = class extends Event { - /** - * Create a new `ErrorEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.error=null] The error that generated this event - * @param {String} [options.message=''] The error message - */ - constructor(type, options = {}) { - super(type); - this[kError] = options.error === void 0 ? null : options.error; - this[kMessage] = options.message === void 0 ? "" : options.message; - } - /** - * @type {*} - */ - get error() { - return this[kError]; - } - /** - * @type {String} - */ - get message() { - return this[kMessage]; - } - }; - Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); - Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); - var MessageEvent = class extends Event { - /** - * Create a new `MessageEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.data=null] The message content - */ - constructor(type, options = {}) { - super(type); - this[kData] = options.data === void 0 ? null : options.data; - } - /** - * @type {*} - */ - get data() { - return this[kData]; - } - }; - Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); - var EventTarget = { - /** - * Register an event listener. - * - * @param {String} type A string representing the event type to listen for - * @param {(Function|Object)} handler The listener to add - * @param {Object} [options] An options object specifies characteristics about - * the event listener - * @param {Boolean} [options.once=false] A `Boolean` indicating that the - * listener should be invoked at most once after being added. If `true`, - * the listener would be automatically removed when invoked. - * @public - */ - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { - return; - } - } - let wrapper; - if (type === "message") { - wrapper = function onMessage(data, isBinary) { - const event = new MessageEvent("message", { - data: isBinary ? data : data.toString() - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "close") { - wrapper = function onClose(code, message) { - const event = new CloseEvent("close", { - code, - reason: message.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "error") { - wrapper = function onError(error) { - const event = new ErrorEvent("error", { - error, - message: error.message - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "open") { - wrapper = function onOpen() { - const event = new Event("open"); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; - } - wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; - wrapper[kListener] = handler; - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); - } - }, - /** - * Remove an event listener. - * - * @param {String} type A string representing the event type to remove - * @param {(Function|Object)} handler The listener to remove - * @public - */ - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { - this.removeListener(type, listener); - break; - } - } - } - }; - module.exports = { - CloseEvent, - ErrorEvent, - Event, - EventTarget, - MessageEvent - }; - function callListener(listener, thisArg, event) { - if (typeof listener === "object" && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); - } - } - } -}); - -// ../../node_modules/ws/lib/extension.js -var require_extension = __commonJS({ - "../../node_modules/ws/lib/extension.js"(exports, module) { - "use strict"; - var { tokenChars } = require_validation(); - function push(dest, name, elem) { - if (dest[name] === void 0) dest[name] = [elem]; - else dest[name].push(elem); - } - function parse(header) { - const offers = /* @__PURE__ */ Object.create(null); - let params = /* @__PURE__ */ Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i = 0; - for (; i < header.length; i++) { - code = header.charCodeAt(i); - if (extensionName === void 0) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (i !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - const name = header.slice(start, end); - if (code === 44) { - push(offers, name, params); - params = /* @__PURE__ */ Object.create(null); - } else { - extensionName = name; - } - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (paramName === void 0) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 32 || code === 9) { - if (end === -1 && start !== -1) end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - push(params, header.slice(start, end), true); - if (code === 44) { - push(offers, extensionName, params); - params = /* @__PURE__ */ Object.create(null); - extensionName = void 0; - } - start = end = -1; - } else if (code === 61 && start !== -1 && end === -1) { - paramName = header.slice(start, i); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else { - if (isEscaping) { - if (tokenChars[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1) start = i; - else if (!mustUnescape) mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 34 && start !== -1) { - inQuotes = false; - end = i; - } else if (code === 92) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (code === 34 && header.charCodeAt(i - 1) === 61) { - inQuotes = true; - } else if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (start !== -1 && (code === 32 || code === 9)) { - if (end === -1) end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ""); - mustUnescape = false; - } - push(params, paramName, value); - if (code === 44) { - push(offers, extensionName, params); - params = /* @__PURE__ */ Object.create(null); - extensionName = void 0; - } - paramName = void 0; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - } - if (start === -1 || inQuotes || code === 32 || code === 9) { - throw new SyntaxError("Unexpected end of input"); - } - if (end === -1) end = i; - const token = header.slice(start, end); - if (extensionName === void 0) { - push(offers, token, params); - } else { - if (paramName === void 0) { - push(params, token, true); - } else if (mustUnescape) { - push(params, paramName, token.replace(/\\/g, "")); - } else { - push(params, paramName, token); - } - push(offers, extensionName, params); - } - return offers; - } - function format(extensions) { - return Object.keys(extensions).map((extension) => { - let configurations = extensions[extension]; - if (!Array.isArray(configurations)) configurations = [configurations]; - return configurations.map((params) => { - return [extension].concat( - Object.keys(params).map((k) => { - let values = params[k]; - if (!Array.isArray(values)) values = [values]; - return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); - }) - ).join("; "); - }).join(", "); - }).join(", "); - } - module.exports = { format, parse }; - } -}); - -// ../../node_modules/ws/lib/websocket.js -var require_websocket = __commonJS({ - "../../node_modules/ws/lib/websocket.js"(exports, module) { - "use strict"; - var EventEmitter = __require("events"); - var https = __require("https"); - var http = __require("http"); - var net = __require("net"); - var tls = __require("tls"); - var { randomBytes, createHash } = __require("crypto"); - var { Duplex, Readable } = __require("stream"); - var { URL } = __require("url"); - var PerMessageDeflate = require_permessage_deflate(); - var Receiver2 = require_receiver(); - var Sender2 = require_sender(); - var { isBlob } = require_validation(); - var { - BINARY_TYPES, - EMPTY_BUFFER, - GUID, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket, - NOOP - } = require_constants(); - var { - EventTarget: { addEventListener, removeEventListener } - } = require_event_target(); - var { format, parse } = require_extension(); - var { toBuffer } = require_buffer_util(); - var closeTimeout = 30 * 1e3; - var kAborted = Symbol("kAborted"); - var protocolVersions = [8, 13]; - var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; - var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - var WebSocket4 = class _WebSocket extends EventEmitter { - /** - * Create a new `WebSocket`. - * - * @param {(String|URL)} address The URL to which to connect - * @param {(String|String[])} [protocols] The subprotocols - * @param {Object} [options] Connection options - */ - constructor(address, protocols, options) { - super(); - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER; - this._closeTimer = null; - this._errorEmitted = false; - this._extensions = {}; - this._paused = false; - this._protocol = ""; - this._readyState = _WebSocket.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - if (protocols === void 0) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === "object" && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - initAsClient(this, address, protocols, options); - } else { - this._autoPong = options.autoPong; - this._isServer = true; - } - } - /** - * For historical reasons, the custom "nodebuffer" type is used by the default - * instead of "blob". - * - * @type {String} - */ - get binaryType() { - return this._binaryType; - } - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) return; - this._binaryType = type; - if (this._receiver) this._receiver._binaryType = type; - } - /** - * @type {Number} - */ - get bufferedAmount() { - if (!this._socket) return this._bufferedAmount; - return this._socket._writableState.length + this._sender._bufferedBytes; - } - /** - * @type {String} - */ - get extensions() { - return Object.keys(this._extensions).join(); - } - /** - * @type {Boolean} - */ - get isPaused() { - return this._paused; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onclose() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onerror() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onopen() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onmessage() { - return null; - } - /** - * @type {String} - */ - get protocol() { - return this._protocol; - } - /** - * @type {Number} - */ - get readyState() { - return this._readyState; - } - /** - * @type {String} - */ - get url() { - return this._url; - } - /** - * Set up the socket and the internal resources. - * - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Object} options Options object - * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.maxPayload=0] The maximum allowed message size - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ - setSocket(socket, head, options) { - const receiver = new Receiver2({ - allowSynchronousEvents: options.allowSynchronousEvents, - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation - }); - const sender = new Sender2(socket, this._extensions, options.generateMask); - this._receiver = receiver; - this._sender = sender; - this._socket = socket; - receiver[kWebSocket] = this; - sender[kWebSocket] = this; - socket[kWebSocket] = this; - receiver.on("conclude", receiverOnConclude); - receiver.on("drain", receiverOnDrain); - receiver.on("error", receiverOnError); - receiver.on("message", receiverOnMessage); - receiver.on("ping", receiverOnPing); - receiver.on("pong", receiverOnPong); - sender.onerror = senderOnError; - if (socket.setTimeout) socket.setTimeout(0); - if (socket.setNoDelay) socket.setNoDelay(); - if (head.length > 0) socket.unshift(head); - socket.on("close", socketOnClose); - socket.on("data", socketOnData); - socket.on("end", socketOnEnd); - socket.on("error", socketOnError); - this._readyState = _WebSocket.OPEN; - this.emit("open"); - } - /** - * Emit the `'close'` event. - * - * @private - */ - emitClose() { - if (!this._socket) { - this._readyState = _WebSocket.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); - return; - } - if (this._extensions[PerMessageDeflate.extensionName]) { - this._extensions[PerMessageDeflate.extensionName].cleanup(); - } - this._receiver.removeAllListeners(); - this._readyState = _WebSocket.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); - } - /** - * Start a closing handshake. - * - * +----------+ +-----------+ +----------+ - * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - - * | +----------+ +-----------+ +----------+ | - * +----------+ +-----------+ | - * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING - * +----------+ +-----------+ | - * | | | +---+ | - * +------------------------+-->|fin| - - - - - * | +---+ | +---+ - * - - - - -|fin|<---------------------+ - * +---+ - * - * @param {Number} [code] Status code explaining why the connection is closing - * @param {(String|Buffer)} [data] The reason why the connection is - * closing - * @public - */ - close(code, data) { - if (this.readyState === _WebSocket.CLOSED) return; - if (this.readyState === _WebSocket.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this.readyState === _WebSocket.CLOSING) { - if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { - this._socket.end(); - } - return; - } - this._readyState = _WebSocket.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - if (err) return; - this._closeFrameSent = true; - if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { - this._socket.end(); - } - }); - setCloseTimer(this); - } - /** - * Pause the socket. - * - * @public - */ - pause() { - if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { - return; - } - this._paused = true; - this._socket.pause(); - } - /** - * Send a ping. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the ping is sent - * @public - */ - ping(data, mask, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof data === "function") { - cb = data; - data = mask = void 0; - } else if (typeof mask === "function") { - cb = mask; - mask = void 0; - } - if (typeof data === "number") data = data.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - if (mask === void 0) mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); - } - /** - * Send a pong. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the pong is sent - * @public - */ - pong(data, mask, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof data === "function") { - cb = data; - data = mask = void 0; - } else if (typeof mask === "function") { - cb = mask; - mask = void 0; - } - if (typeof data === "number") data = data.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - if (mask === void 0) mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); - } - /** - * Resume the socket. - * - * @public - */ - resume() { - if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { - return; - } - this._paused = false; - if (!this._receiver._writableState.needDrain) this._socket.resume(); - } - /** - * Send a data message. - * - * @param {*} data The message to send - * @param {Object} [options] Options object - * @param {Boolean} [options.binary] Specifies whether `data` is binary or - * text - * @param {Boolean} [options.compress] Specifies whether or not to compress - * `data` - * @param {Boolean} [options.fin=true] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when data is written out - * @public - */ - send(data, options, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof options === "function") { - cb = options; - options = {}; - } - if (typeof data === "number") data = data.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - const opts = { - binary: typeof data !== "string", - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - if (!this._extensions[PerMessageDeflate.extensionName]) { - opts.compress = false; - } - this._sender.send(data || EMPTY_BUFFER, opts, cb); - } - /** - * Forcibly close the connection. - * - * @public - */ - terminate() { - if (this.readyState === _WebSocket.CLOSED) return; - if (this.readyState === _WebSocket.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this._socket) { - this._readyState = _WebSocket.CLOSING; - this._socket.destroy(); - } - } - }; - Object.defineProperty(WebSocket4, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket4.prototype, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket4, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket4.prototype, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket4, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket4.prototype, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket4, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - Object.defineProperty(WebSocket4.prototype, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - [ - "binaryType", - "bufferedAmount", - "extensions", - "isPaused", - "protocol", - "readyState", - "url" - ].forEach((property) => { - Object.defineProperty(WebSocket4.prototype, property, { enumerable: true }); - }); - ["open", "error", "close", "message"].forEach((method) => { - Object.defineProperty(WebSocket4.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) return listener[kListener]; - } - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; - } - } - if (typeof handler !== "function") return; - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); - }); - WebSocket4.prototype.addEventListener = addEventListener; - WebSocket4.prototype.removeEventListener = removeEventListener; - module.exports = WebSocket4; - function initAsClient(websocket, address, protocols, options) { - const opts = { - allowSynchronousEvents: true, - autoPong: true, - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - socketPath: void 0, - hostname: void 0, - protocol: void 0, - timeout: void 0, - method: "GET", - host: void 0, - path: void 0, - port: void 0 - }; - websocket._autoPong = opts.autoPong; - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` - ); - } - let parsedUrl; - if (address instanceof URL) { - parsedUrl = address; - } else { - try { - parsedUrl = new URL(address); - } catch (e) { - throw new SyntaxError(`Invalid URL: ${address}`); - } - } - if (parsedUrl.protocol === "http:") { - parsedUrl.protocol = "ws:"; - } else if (parsedUrl.protocol === "https:") { - parsedUrl.protocol = "wss:"; - } - websocket._url = parsedUrl.href; - const isSecure = parsedUrl.protocol === "wss:"; - const isIpcUrl = parsedUrl.protocol === "ws+unix:"; - let invalidUrlMessage; - if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { - invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = "The URL contains a fragment identifier"; - } - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - if (websocket._redirects === 0) { - throw err; - } else { - emitErrorAndClose(websocket, err); - return; - } - } - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString("base64"); - const request = isSecure ? https.request : http.request; - const protocolSet = /* @__PURE__ */ new Set(); - let perMessageDeflate; - opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - "Sec-WebSocket-Version": opts.protocolVersion, - "Sec-WebSocket-Key": key, - Connection: "Upgrade", - Upgrade: "websocket" - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate( - opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, - false, - opts.maxPayload - ); - opts.headers["Sec-WebSocket-Extensions"] = format({ - [PerMessageDeflate.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols.length) { - for (const protocol of protocols) { - if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { - throw new SyntaxError( - "An invalid or duplicated subprotocol was specified" - ); - } - protocolSet.add(protocol); - } - opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers["Sec-WebSocket-Origin"] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - if (isIpcUrl) { - const parts = opts.path.split(":"); - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - let req; - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; - const headers = options && options.headers; - options = { ...options, headers: {} }; - if (headers) { - for (const [key2, value] of Object.entries(headers)) { - options.headers[key2.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount("redirect") === 0) { - const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; - if (!isSameHost || websocket._originalSecure && !isSecure) { - delete opts.headers.authorization; - delete opts.headers.cookie; - if (!isSameHost) delete opts.headers.host; - opts.auth = void 0; - } - } - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); - } - req = websocket._req = request(opts); - if (websocket._redirects) { - websocket.emit("redirect", websocket.url, req); - } - } else { - req = websocket._req = request(opts); - } - if (opts.timeout) { - req.on("timeout", () => { - abortHandshake(websocket, req, "Opening handshake has timed out"); - }); - } - req.on("error", (err) => { - if (req === null || req[kAborted]) return; - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - req.on("response", (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake(websocket, req, "Maximum redirects exceeded"); - return; - } - req.abort(); - let addr; - try { - addr = new URL(location, address); - } catch (e) { - const err = new SyntaxError(`Invalid URL: ${location}`); - emitErrorAndClose(websocket, err); - return; - } - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit("unexpected-response", req, res)) { - abortHandshake( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - req.on("upgrade", (res, socket, head) => { - websocket.emit("upgrade", res); - if (websocket.readyState !== WebSocket4.CONNECTING) return; - req = websocket._req = null; - const upgrade = res.headers.upgrade; - if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { - abortHandshake(websocket, socket, "Invalid Upgrade header"); - return; - } - const digest = createHash("sha1").update(key + GUID).digest("base64"); - if (res.headers["sec-websocket-accept"] !== digest) { - abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); - return; - } - const serverProt = res.headers["sec-websocket-protocol"]; - let protError; - if (serverProt !== void 0) { - if (!protocolSet.size) { - protError = "Server sent a subprotocol but none was requested"; - } else if (!protocolSet.has(serverProt)) { - protError = "Server sent an invalid subprotocol"; - } - } else if (protocolSet.size) { - protError = "Server sent no subprotocol"; - } - if (protError) { - abortHandshake(websocket, socket, protError); - return; - } - if (serverProt) websocket._protocol = serverProt; - const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; - if (secWebSocketExtensions !== void 0) { - if (!perMessageDeflate) { - const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; - abortHandshake(websocket, socket, message); - return; - } - let extensions; - try { - extensions = parse(secWebSocketExtensions); - } catch (err) { - const message = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message); - return; - } - const extensionNames = Object.keys(extensions); - if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { - const message = "Server indicated an extension that was not requested"; - abortHandshake(websocket, socket, message); - return; - } - try { - perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); - } catch (err) { - const message = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message); - return; - } - websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - websocket.setSocket(socket, head, { - allowSynchronousEvents: opts.allowSynchronousEvents, - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } - } - function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket4.CLOSING; - websocket._errorEmitted = true; - websocket.emit("error", err); - websocket.emitClose(); - } - function netConnect(options) { - options.path = options.socketPath; - return net.connect(options); - } - function tlsConnect(options) { - options.path = void 0; - if (!options.servername && options.servername !== "") { - options.servername = net.isIP(options.host) ? "" : options.host; - } - return tls.connect(options); - } - function abortHandshake(websocket, stream, message) { - websocket._readyState = WebSocket4.CLOSING; - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake); - if (stream.setHeader) { - stream[kAborted] = true; - stream.abort(); - if (stream.socket && !stream.socket.destroyed) { - stream.socket.destroy(); - } - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream.destroy(err); - stream.once("error", websocket.emit.bind(websocket, "error")); - stream.once("close", websocket.emitClose.bind(websocket)); - } - } - function sendAfterClose(websocket, data, cb) { - if (data) { - const length = isBlob(data) ? data.size : toBuffer(data).length; - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` - ); - process.nextTick(cb, err); - } - } - function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket]; - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - if (websocket._socket[kWebSocket] === void 0) return; - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - if (code === 1005) websocket.close(); - else websocket.close(code, reason); - } - function receiverOnDrain() { - const websocket = this[kWebSocket]; - if (!websocket.isPaused) websocket._socket.resume(); - } - function receiverOnError(err) { - const websocket = this[kWebSocket]; - if (websocket._socket[kWebSocket] !== void 0) { - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - websocket.close(err[kStatusCode]); - } - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); - } - } - function receiverOnFinish() { - this[kWebSocket].emitClose(); - } - function receiverOnMessage(data, isBinary) { - this[kWebSocket].emit("message", data, isBinary); - } - function receiverOnPing(data) { - const websocket = this[kWebSocket]; - if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); - websocket.emit("ping", data); - } - function receiverOnPong(data) { - this[kWebSocket].emit("pong", data); - } - function resume(stream) { - stream.resume(); - } - function senderOnError(err) { - const websocket = this[kWebSocket]; - if (websocket.readyState === WebSocket4.CLOSED) return; - if (websocket.readyState === WebSocket4.OPEN) { - websocket._readyState = WebSocket4.CLOSING; - setCloseTimer(websocket); - } - this._socket.end(); - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); - } - } - function setCloseTimer(websocket) { - websocket._closeTimer = setTimeout( - websocket._socket.destroy.bind(websocket._socket), - closeTimeout - ); - } - function socketOnClose() { - const websocket = this[kWebSocket]; - this.removeListener("close", socketOnClose); - this.removeListener("data", socketOnData); - this.removeListener("end", socketOnEnd); - websocket._readyState = WebSocket4.CLOSING; - let chunk; - if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { - websocket._receiver.write(chunk); - } - websocket._receiver.end(); - this[kWebSocket] = void 0; - clearTimeout(websocket._closeTimer); - if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { - websocket.emitClose(); - } else { - websocket._receiver.on("error", receiverOnFinish); - websocket._receiver.on("finish", receiverOnFinish); - } - } - function socketOnData(chunk) { - if (!this[kWebSocket]._receiver.write(chunk)) { - this.pause(); - } - } - function socketOnEnd() { - const websocket = this[kWebSocket]; - websocket._readyState = WebSocket4.CLOSING; - websocket._receiver.end(); - this.end(); - } - function socketOnError() { - const websocket = this[kWebSocket]; - this.removeListener("error", socketOnError); - this.on("error", NOOP); - if (websocket) { - websocket._readyState = WebSocket4.CLOSING; - this.destroy(); - } - } - } -}); - -// ../../node_modules/ws/lib/subprotocol.js -var require_subprotocol = __commonJS({ - "../../node_modules/ws/lib/subprotocol.js"(exports, module) { - "use strict"; - var { tokenChars } = require_validation(); - function parse(header) { - const protocols = /* @__PURE__ */ new Set(); - let start = -1; - let end = -1; - let i = 0; - for (i; i < header.length; i++) { - const code = header.charCodeAt(i); - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (i !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) end = i; - } else if (code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - const protocol2 = header.slice(start, end); - if (protocols.has(protocol2)) { - throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); - } - protocols.add(protocol2); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - if (start === -1 || end !== -1) { - throw new SyntaxError("Unexpected end of input"); - } - const protocol = header.slice(start, i); - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - protocols.add(protocol); - return protocols; - } - module.exports = { parse }; - } -}); - -// ../../node_modules/ws/lib/websocket-server.js -var require_websocket_server = __commonJS({ - "../../node_modules/ws/lib/websocket-server.js"(exports, module) { - "use strict"; - var EventEmitter = __require("events"); - var http = __require("http"); - var { Duplex } = __require("stream"); - var { createHash } = __require("crypto"); - var extension = require_extension(); - var PerMessageDeflate = require_permessage_deflate(); - var subprotocol = require_subprotocol(); - var WebSocket4 = require_websocket(); - var { GUID, kWebSocket } = require_constants(); - var keyRegex = /^[+/0-9A-Za-z]{22}==$/; - var RUNNING = 0; - var CLOSING = 1; - var CLOSED = 2; - var WebSocketServer2 = class extends EventEmitter { - /** - * Create a `WebSocketServer` instance. - * - * @param {Object} options Configuration options - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Boolean} [options.autoPong=true] Specifies whether or not to - * automatically send a pong in response to a ping - * @param {Number} [options.backlog=511] The maximum length of the queue of - * pending connections - * @param {Boolean} [options.clientTracking=true] Specifies whether or not to - * track clients - * @param {Function} [options.handleProtocols] A hook to handle protocols - * @param {String} [options.host] The hostname where to bind the server - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.noServer=false] Enable no server mode - * @param {String} [options.path] Accept only connections matching this path - * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable - * permessage-deflate - * @param {Number} [options.port] The port where to bind the server - * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S - * server to use - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @param {Function} [options.verifyClient] A hook to reject connections - * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` - * class to use. It must be the `WebSocket` class or class that extends it - * @param {Function} [callback] A listener for the `listening` event - */ - constructor(options, callback) { - super(); - options = { - allowSynchronousEvents: true, - autoPong: true, - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - verifyClient: null, - noServer: false, - backlog: null, - // use default (511 as implemented in net.js) - server: null, - host: null, - path: null, - port: null, - WebSocket: WebSocket4, - ...options - }; - if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { - throw new TypeError( - 'One and only one of the "port", "server", or "noServer" options must be specified' - ); - } - if (options.port != null) { - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - res.writeHead(426, { - "Content-Length": body.length, - "Content-Type": "text/plain" - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - if (this._server) { - const emitConnection = this.emit.bind(this, "connection"); - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, "listening"), - error: this.emit.bind(this, "error"), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = /* @__PURE__ */ new Set(); - this._shouldEmitClose = false; - } - this.options = options; - this._state = RUNNING; - } - /** - * Returns the bound address, the address family name, and port of the server - * as reported by the operating system if listening on an IP socket. - * If the server is listening on a pipe or UNIX domain socket, the name is - * returned as a string. - * - * @return {(Object|String|null)} The address of the server - * @public - */ - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - if (!this._server) return null; - return this._server.address(); - } - /** - * Stop the server from accepting new connections and emit the `'close'` event - * when all existing connections are closed. - * - * @param {Function} [cb] A one-time listener for the `'close'` event - * @public - */ - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once("close", () => { - cb(new Error("The server is not running")); - }); - } - process.nextTick(emitClose, this); - return; - } - if (cb) this.once("close", cb); - if (this._state === CLOSING) return; - this._state = CLOSING; - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - this._removeListeners(); - this._removeListeners = this._server = null; - server.close(() => { - emitClose(this); - }); - } - } - /** - * See if a given request should be handled by this server instance. - * - * @param {http.IncomingMessage} req Request object to inspect - * @return {Boolean} `true` if the request is valid, else `false` - * @public - */ - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf("?"); - const pathname = index !== -1 ? req.url.slice(0, index) : req.url; - if (pathname !== this.options.path) return false; - } - return true; - } - /** - * Handle a HTTP Upgrade request. - * - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @public - */ - handleUpgrade(req, socket, head, cb) { - socket.on("error", socketOnError); - const key = req.headers["sec-websocket-key"]; - const upgrade = req.headers.upgrade; - const version = +req.headers["sec-websocket-version"]; - if (req.method !== "GET") { - const message = "Invalid HTTP method"; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); - return; - } - if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { - const message = "Invalid Upgrade header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (key === void 0 || !keyRegex.test(key)) { - const message = "Missing or invalid Sec-WebSocket-Key header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (version !== 8 && version !== 13) { - const message = "Missing or invalid Sec-WebSocket-Version header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; - let protocols = /* @__PURE__ */ new Set(); - if (secWebSocketProtocol !== void 0) { - try { - protocols = subprotocol.parse(secWebSocketProtocol); - } catch (err) { - const message = "Invalid Sec-WebSocket-Protocol header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; - const extensions = {}; - if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { - const perMessageDeflate = new PerMessageDeflate( - this.options.perMessageDeflate, - true, - this.options.maxPayload - ); - try { - const offers = extension.parse(secWebSocketExtensions); - if (offers[PerMessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); - extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - if (this.options.verifyClient) { - const info = { - origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - this.completeUpgrade( - extensions, - key, - protocols, - req, - socket, - head, - cb - ); - }); - return; - } - if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } - /** - * Upgrade the connection to WebSocket. - * - * @param {Object} extensions The accepted extensions - * @param {String} key The value of the `Sec-WebSocket-Key` header - * @param {Set} protocols The subprotocols - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @throws {Error} If called more than once with the same socket - * @private - */ - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - if (!socket.readable || !socket.writable) return socket.destroy(); - if (socket[kWebSocket]) { - throw new Error( - "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" - ); - } - if (this._state > RUNNING) return abortHandshake(socket, 503); - const digest = createHash("sha1").update(key + GUID).digest("base64"); - const headers = [ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - `Sec-WebSocket-Accept: ${digest}` - ]; - const ws = new this.options.WebSocket(null, void 0, this.options); - if (protocols.size) { - const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - if (extensions[PerMessageDeflate.extensionName]) { - const params = extensions[PerMessageDeflate.extensionName].params; - const value = extension.format({ - [PerMessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - this.emit("headers", headers, req); - socket.write(headers.concat("\r\n").join("\r\n")); - socket.removeListener("error", socketOnError); - ws.setSocket(socket, head, { - allowSynchronousEvents: this.options.allowSynchronousEvents, - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - if (this.clients) { - this.clients.add(ws); - ws.on("close", () => { - this.clients.delete(ws); - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - cb(ws, req); - } - }; - module.exports = WebSocketServer2; - function addListeners(server, map) { - for (const event of Object.keys(map)) server.on(event, map[event]); - return function removeListeners() { - for (const event of Object.keys(map)) { - server.removeListener(event, map[event]); - } - }; - } - function emitClose(server) { - server._state = CLOSED; - server.emit("close"); - } - function socketOnError() { - this.destroy(); - } - function abortHandshake(socket, code, message, headers) { - message = message || http.STATUS_CODES[code]; - headers = { - Connection: "close", - "Content-Type": "text/html", - "Content-Length": Buffer.byteLength(message), - ...headers - }; - socket.once("finish", socket.destroy); - socket.end( - `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r -` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message - ); - } - function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { - if (server.listenerCount("wsClientError")) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - server.emit("wsClientError", err, socket, req); - } else { - abortHandshake(socket, code, message); - } - } - } -}); - -// ../../node_modules/ws/wrapper.mjs -var wrapper_exports = {}; -__export(wrapper_exports, { - Receiver: () => import_receiver.default, - Sender: () => import_sender.default, - WebSocket: () => import_websocket.default, - WebSocketServer: () => import_websocket_server.default, - createWebSocketStream: () => import_stream.default, - default: () => wrapper_default -}); -var import_stream = __toESM(require_stream(), 1); -var import_receiver = __toESM(require_receiver(), 1); -var import_sender = __toESM(require_sender(), 1); -var import_websocket = __toESM(require_websocket(), 1); -var import_websocket_server = __toESM(require_websocket_server(), 1); -var wrapper_default = import_websocket.default; - -// ../../node_modules/isows/_esm/utils.js -function getNativeWebSocket() { - if (typeof WebSocket !== "undefined") - return WebSocket; - if (typeof global.WebSocket !== "undefined") - return global.WebSocket; - if (typeof window.WebSocket !== "undefined") - return window.WebSocket; - if (typeof self.WebSocket !== "undefined") - return self.WebSocket; - throw new Error("`WebSocket` is not supported in this environment"); -} - -// ../../node_modules/isows/_esm/index.js -var WebSocket3 = (() => { - try { - return getNativeWebSocket(); - } catch { - if (import_websocket.default) - return import_websocket.default; - return wrapper_exports; - } -})(); -export { - WebSocket3 as WebSocket -}; -//# sourceMappingURL=_esm-L4OBJJWB.js.map \ No newline at end of file diff --git a/dist/_esm-L4OBJJWB.js.map b/dist/_esm-L4OBJJWB.js.map deleted file mode 100644 index 74eb313..0000000 --- a/dist/_esm-L4OBJJWB.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../node_modules/ws/lib/stream.js","../../../node_modules/ws/lib/constants.js","../../../node_modules/node-gyp-build/node-gyp-build.js","../../../node_modules/node-gyp-build/index.js","../../../node_modules/bufferutil/fallback.js","../../../node_modules/bufferutil/index.js","../../../node_modules/ws/lib/buffer-util.js","../../../node_modules/ws/lib/limiter.js","../../../node_modules/ws/lib/permessage-deflate.js","../../../node_modules/utf-8-validate/fallback.js","../../../node_modules/utf-8-validate/index.js","../../../node_modules/ws/lib/validation.js","../../../node_modules/ws/lib/receiver.js","../../../node_modules/ws/lib/sender.js","../../../node_modules/ws/lib/event-target.js","../../../node_modules/ws/lib/extension.js","../../../node_modules/ws/lib/websocket.js","../../../node_modules/ws/lib/subprotocol.js","../../../node_modules/ws/lib/websocket-server.js","../../../node_modules/ws/wrapper.mjs","../../../node_modules/isows/utils.ts","../../../node_modules/isows/index.ts"],"sourcesContent":["'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/-\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of \n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","export function getNativeWebSocket() {\n if (typeof WebSocket !== \"undefined\") return WebSocket;\n if (typeof global.WebSocket !== \"undefined\") return global.WebSocket;\n if (typeof window.WebSocket !== \"undefined\") return window.WebSocket;\n if (typeof self.WebSocket !== \"undefined\") return self.WebSocket;\n throw new Error(\"`WebSocket` is not supported in this environment\");\n}\n","import * as WebSocket_ from \"ws\";\nimport { getNativeWebSocket } from \"./utils.js\";\n\nexport const WebSocket = (() => {\n try {\n return getNativeWebSocket();\n } catch {\n if (WebSocket_.WebSocket) return WebSocket_.WebSocket;\n return WebSocket_;\n }\n})();\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,EAAE,OAAO,IAAI,UAAQ,QAAQ;AAQnC,aAAS,UAAU,QAAQ;AACzB,aAAO,KAAK,OAAO;AAAA,IACrB;AAOA,aAAS,cAAc;AACrB,UAAI,CAAC,KAAK,aAAa,KAAK,eAAe,UAAU;AACnD,aAAK,QAAQ;AAAA,MACf;AAAA,IACF;AAQA,aAAS,cAAc,KAAK;AAC1B,WAAK,eAAe,SAAS,aAAa;AAC1C,WAAK,QAAQ;AACb,UAAI,KAAK,cAAc,OAAO,MAAM,GAAG;AAErC,aAAK,KAAK,SAAS,GAAG;AAAA,MACxB;AAAA,IACF;AAUA,aAASA,uBAAsB,IAAI,SAAS;AAC1C,UAAI,qBAAqB;AAEzB,YAAM,SAAS,IAAI,OAAO;AAAA,QACxB,GAAG;AAAA,QACH,aAAa;AAAA,QACb,WAAW;AAAA,QACX,YAAY;AAAA,QACZ,oBAAoB;AAAA,MACtB,CAAC;AAED,SAAG,GAAG,WAAW,SAAS,QAAQ,KAAK,UAAU;AAC/C,cAAM,OACJ,CAAC,YAAY,OAAO,eAAe,aAAa,IAAI,SAAS,IAAI;AAEnE,YAAI,CAAC,OAAO,KAAK,IAAI,EAAG,IAAG,MAAM;AAAA,MACnC,CAAC;AAED,SAAG,KAAK,SAAS,SAAS,MAAM,KAAK;AACnC,YAAI,OAAO,UAAW;AAWtB,6BAAqB;AACr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AAO,KAAK,UAAU,OAAO,OAAO;AAEpC,aAAO;AAAA,QACL,YAAY,IAAI,IAAI,KAAK,aAAa,IAAI,CAAC;AAAA,IACzC,OAAO,KAAK,OAAO,EAChB,IAAI,CAAC,MAAM,GAAG,CAAC,KAAK,QAAQ,CAAC,CAAC,EAAE,EAChC,KAAK,MAAM,IACd,aACA;AAAA,MACJ;AAAA,IACF;AAaA,aAAS,kCAAkC,QAAQ,KAAK,QAAQ,MAAM,SAAS;AAC7E,UAAI,OAAO,cAAc,eAAe,GAAG;AACzC,cAAM,MAAM,IAAI,MAAM,OAAO;AAC7B,cAAM,kBAAkB,KAAK,iCAAiC;AAE9D,eAAO,KAAK,iBAAiB,KAAK,QAAQ,GAAG;AAAA,MAC/C,OAAO;AACL,uBAAe,QAAQ,MAAM,OAAO;AAAA,MACtC;AAAA,IACF;AAAA;AAAA;;;AC3hBA;AAAA;AAAA,kCAAAC;AAAA,EAAA,4BAAAC;AAAA,EAAA,kCAAAC;AAAA,EAAA,+CAAAC;AAAA,EAAA,2CAAAC;AAAA,EAAA;AAAA;AAAA,oBAAkC;AAClC,sBAAqB;AACrB,oBAAmB;AACnB,uBAAsB;AACtB,8BAA4B;AAG5B,IAAO,kBAAQ,iBAAAC;;;ACPT,SAAU,qBAAkB;AAChC,MAAI,OAAO,cAAc;AAAa,WAAO;AAC7C,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,OAAO,cAAc;AAAa,WAAO,OAAO;AAC3D,MAAI,OAAO,KAAK,cAAc;AAAa,WAAO,KAAK;AACvD,QAAM,IAAI,MAAM,kDAAkD;AACpE;;;ACHO,IAAMC,cAAa,MAAK;AAC7B,MAAI;AACF,WAAO,mBAAkB;EAC3B,QAAQ;AACN,QAAe,iBAAAA;AAAW,aAAkB,iBAAAA;AAC5C,WAAO;EACT;AACF,GAAE;","names":["createWebSocketStream","err","dir","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","Receiver","Sender","Receiver","Sender","WebSocket","key","protocol","WebSocket","WebSocketServer","Receiver","Sender","WebSocket","WebSocketServer","createWebSocketStream","WebSocket","WebSocket"]} \ No newline at end of file diff --git a/dist/ccip-MMGH6DXX.js b/dist/ccip-MMGH6DXX.js deleted file mode 100644 index 95194f6..0000000 --- a/dist/ccip-MMGH6DXX.js +++ /dev/null @@ -1,14 +0,0 @@ -import { - ccipRequest, - offchainLookup, - offchainLookupAbiItem, - offchainLookupSignature -} from "./chunk-NTU6R7BC.js"; -import "./chunk-PR4QN5HX.js"; -export { - ccipRequest, - offchainLookup, - offchainLookupAbiItem, - offchainLookupSignature -}; -//# sourceMappingURL=ccip-MMGH6DXX.js.map \ No newline at end of file diff --git a/dist/ccip-MMGH6DXX.js.map b/dist/ccip-MMGH6DXX.js.map deleted file mode 100644 index 84c51b2..0000000 --- a/dist/ccip-MMGH6DXX.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/dist/chunk-4L6P6TY5.js b/dist/chunk-4L6P6TY5.js deleted file mode 100644 index 973ee43..0000000 --- a/dist/chunk-4L6P6TY5.js +++ /dev/null @@ -1,2556 +0,0 @@ -import { - __export -} from "./chunk-PR4QN5HX.js"; - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js -function anumber(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error("positive integer expected, got " + n); -} -function isBytes(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes(b, ...lengths) { - if (!isBytes(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); -} -function ahash(h) { - if (typeof h !== "function" || typeof h.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - anumber(h.outputLen); - anumber(h.blockLen); -} -function aexists(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 aoutput(out, instance) { - abytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least " + min); - } -} - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/cryptoNode.js -import * as nc from "node:crypto"; -var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js -var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -var rotr = (word, shift) => word << 32 - shift | word >>> shift; -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error("utf8ToBytes expected string, got " + typeof str); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - abytes(data); - return data; -} -function concatBytes(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad); - pad += a.length; - } - return res; -} -var Hash = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -}; -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function randomBytes(bytesLength = 32) { - if (crypto && typeof crypto.getRandomValues === "function") { - return crypto.getRandomValues(new Uint8Array(bytesLength)); - } - if (crypto && typeof crypto.randomBytes === "function") { - return crypto.randomBytes(bytesLength); - } - throw new Error("crypto.getRandomValues must be defined"); -} - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_md.js -function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); -} -var Chi = (a, b, c) => a & b ^ ~a & c; -var Maj = (a, b, c) => a & b ^ a & c ^ b & c; -var HashMD = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - aexists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } -}; - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js -var SHA256_K = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -var SHA256_IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA256_W = /* @__PURE__ */ new Uint32Array(64); -var SHA256 = class extends HashMD { - constructor() { - super(64, 32, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } -}; -var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); - -// ../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js -var HMAC = class extends Hash { - constructor(hash, _key) { - super(); - this.finished = false; - this.destroyed = false; - ahash(hash); - const key = toBytes(_key); - this.iHash = hash.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; - this.iHash.update(pad); - this.oHash = hash.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - abytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -}; -var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); -hmac.create = (hash, key) => new HMAC(hash, key); - -// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js -var utils_exports = {}; -__export(utils_exports, { - aInRange: () => aInRange, - abool: () => abool, - abytes: () => abytes2, - bitGet: () => bitGet, - bitLen: () => bitLen, - bitMask: () => bitMask, - bitSet: () => bitSet, - bytesToHex: () => bytesToHex, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes2, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes, - hexToNumber: () => hexToNumber, - inRange: () => inRange, - isBytes: () => isBytes2, - memoized: () => memoized, - notImplemented: () => notImplemented, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes2, - validateObject: () => validateObject -}); -var _0n = /* @__PURE__ */ BigInt(0); -var _1n = /* @__PURE__ */ BigInt(1); -var _2n = /* @__PURE__ */ BigInt(2); -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes2(item) { - if (!isBytes2(item)) - throw new Error("Uint8Array expected"); -} -function abool(title, value) { - if (typeof value !== "boolean") - throw new Error(title + " boolean expected, got " + value); -} -var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex(bytes) { - abytes2(bytes); - let hex = ""; - for (let i = 0; i < bytes.length; i++) { - hex += hexes[bytes[i]]; - } - return hex; -} -function numberToHexUnpadded(num2) { - const hex = num2.toString(16); - return hex.length & 1 ? "0" + hex : hex; -} -function hexToNumber(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - return hex === "" ? _0n : BigInt("0x" + hex); -} -var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - const hl = hex.length; - const al = hl / 2; - if (hl % 2) - throw new Error("hex string expected, got unpadded hex of length " + hl); - const array = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex.charCodeAt(hi)); - const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex[hi] + hex[hi + 1]; - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array[ai] = n1 * 16 + n2; - } - return array; -} -function bytesToNumberBE(bytes) { - return hexToNumber(bytesToHex(bytes)); -} -function bytesToNumberLE(bytes) { - abytes2(bytes); - return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); -} -function numberToBytesBE(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, "0")); -} -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); -} -function numberToVarBytesBE(n) { - return hexToBytes(numberToHexUnpadded(n)); -} -function ensureBytes(title, hex, expectedLength) { - let res; - if (typeof hex === "string") { - try { - res = hexToBytes(hex); - } catch (e) { - throw new Error(title + " must be hex string or Uint8Array, cause: " + e); - } - } else if (isBytes2(hex)) { - res = Uint8Array.from(hex); - } else { - throw new Error(title + " must be hex string or Uint8Array"); - } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(title + " of length " + expectedLength + " expected, got " + len); - return res; -} -function concatBytes2(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes2(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad); - pad += a.length; - } - return res; -} -function equalBytes(a, b) { - if (a.length !== b.length) - return false; - let diff = 0; - for (let i = 0; i < a.length; i++) - diff |= a[i] ^ b[i]; - return diff === 0; -} -function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -var isPosBig = (n) => typeof n === "bigint" && _0n <= n; -function inRange(n, min, max) { - return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; -} -function aInRange(title, n, min, max) { - if (!inRange(n, min, max)) - throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); -} -function bitLen(n) { - let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; - return len; -} -function bitGet(n, pos) { - return n >> BigInt(pos) & _1n; -} -function bitSet(n, pos, value) { - return n | (value ? _1n : _0n) << BigInt(pos); -} -var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; -var u8n = (data) => new Uint8Array(data); -var u8fr = (arr) => Uint8Array.from(arr); -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n()) => { - k = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8fr([1]), seed); - v = h(); - }; - const gen = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes2(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; -} -var validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) -}; -function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error("invalid validator function"); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; -} -var notImplemented = () => { - throw new Error("not implemented"); -}; -function memoized(fn) { - const map = /* @__PURE__ */ new WeakMap(); - return (arg, ...args) => { - const val = map.get(arg); - if (val !== void 0) - return val; - const computed = fn(arg, ...args); - map.set(arg, computed); - return computed; - }; -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js -var _0n2 = BigInt(0); -var _1n2 = BigInt(1); -var _2n2 = /* @__PURE__ */ BigInt(2); -var _3n = /* @__PURE__ */ BigInt(3); -var _4n = /* @__PURE__ */ BigInt(4); -var _5n = /* @__PURE__ */ BigInt(5); -var _8n = /* @__PURE__ */ BigInt(8); -var _9n = /* @__PURE__ */ BigInt(9); -var _16n = /* @__PURE__ */ BigInt(16); -function mod(a, b) { - const result = a % b; - return result >= _0n2 ? result : b + result; -} -function pow(num2, power, modulo) { - if (power < _0n2) - throw new Error("invalid exponent, negatives unsupported"); - if (modulo <= _0n2) - throw new Error("invalid modulus"); - if (modulo === _1n2) - return _0n2; - let res = _1n2; - while (power > _0n2) { - if (power & _1n2) - res = res * num2 % modulo; - num2 = num2 * num2 % modulo; - power >>= _1n2; - } - return res; -} -function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; -} -function invert(number, modulo) { - if (number === _0n2) - throw new Error("invert: expected non-zero number"); - if (modulo <= _0n2) - throw new Error("invert: expected positive modulus, got " + modulo); - let a = mod(number, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd = b; - if (gcd !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); -} -function tonelliShanks(P) { - const legendreC = (P - _1n2) / _2n2; - let Q, S, Z; - for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) { - if (Z > 1e3) - throw new Error("Cannot find square root: likely non-prime P"); - } - if (S === 1) { - const p1div4 = (P + _1n2) / _4n; - return function tonelliFast(Fp, n) { - const root = Fp.pow(n, p1div4); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - const Q1div2 = (Q + _1n2) / _2n2; - return function tonelliSlow(Fp, n) { - if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); - let x = Fp.pow(n, Q1div2); - let b = Fp.pow(n, Q); - while (!Fp.eql(b, Fp.ONE)) { - if (Fp.eql(b, Fp.ZERO)) - return Fp.ZERO; - let m = 1; - for (let t2 = Fp.sqr(b); m < r; m++) { - if (Fp.eql(t2, Fp.ONE)) - break; - t2 = Fp.sqr(t2); - } - const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1)); - g = Fp.sqr(ge); - x = Fp.mul(x, ge); - b = Fp.mul(b, g); - r = m; - } - return x; - }; -} -function FpSqrt(P) { - if (P % _4n === _3n) { - const p1div4 = (P + _1n2) / _4n; - return function sqrt3mod4(Fp, n) { - const root = Fp.pow(n, p1div4); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _8n === _5n) { - const c1 = (P - _5n) / _8n; - return function sqrt5mod8(Fp, n) { - const n2 = Fp.mul(n, _2n2); - const v = Fp.pow(n2, c1); - const nv = Fp.mul(n, v); - const i = Fp.mul(Fp.mul(nv, _2n2), v); - const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _16n === _9n) { - } - return tonelliShanks(P); -} -var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" -]; -function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); -} -function FpPow(f, num2, power) { - if (power < _0n2) - throw new Error("invalid exponent, negatives unsupported"); - if (power === _0n2) - return f.ONE; - if (power === _1n2) - return num2; - let p = f.ONE; - let d = num2; - while (power > _0n2) { - if (power & _1n2) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n2; - } - return p; -} -function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num2, i) => { - if (f.is0(num2)) - return acc; - tmp[i] = acc; - return f.mul(acc, num2); - }, f.ONE); - const inverted = f.inv(lastMultiplied); - nums.reduceRight((acc, num2, i) => { - if (f.is0(num2)) - return acc; - tmp[i] = f.mul(acc, tmp[i]); - return f.mul(acc, num2); - }, inverted); - return tmp; -} -function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; -} -function Field(ORDER, bitLen2, isLE = false, redef = {}) { - if (ORDER <= _0n2) - throw new Error("invalid field: expected ORDER > 0, got " + ORDER); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("invalid field: expected ORDER of <= 2048 bytes"); - let sqrtP; - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n2, - ONE: _1n2, - create: (num2) => mod(num2, ORDER), - isValid: (num2) => { - if (typeof num2 !== "bigint") - throw new Error("invalid field element: expected bigint, got " + typeof num2); - return _0n2 <= num2 && num2 < ORDER; - }, - is0: (num2) => num2 === _0n2, - isOdd: (num2) => (num2 & _1n2) === _1n2, - neg: (num2) => mod(-num2, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num2) => mod(num2 * num2, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num2, power) => FpPow(f, num2, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num2) => num2 * num2, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num2) => invert(num2, ORDER), - sqrt: redef.sqrt || ((n) => { - if (!sqrtP) - sqrtP = FpSqrt(ORDER); - return sqrtP(f, n); - }), - invertBatch: (lst) => FpInvertBatch(f, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a, b, c) => c ? b : a, - toBytes: (num2) => isLE ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), - fromBytes: (bytes) => { - if (bytes.length !== BYTES) - throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); - return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); - } - }); - return Object.freeze(f); -} -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); -} -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); -} -function mapHashToField(key, fieldOrder, isLE = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); - const num2 = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); - const reduced = mod(num2, fieldOrder - _1n2) + _1n2; - return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js -var _0n3 = BigInt(0); -var _1n3 = BigInt(1); -function constTimeNegate(condition, item) { - const neg = item.negate(); - return condition ? neg : item; -} -function validateW(W, bits) { - if (!Number.isSafeInteger(W) || W <= 0 || W > bits) - throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); -} -function calcWOpts(W, bits) { - validateW(W, bits); - const windows = Math.ceil(bits / W) + 1; - const windowSize = 2 ** (W - 1); - return { windows, windowSize }; -} -function validateMSMPoints(points, c) { - if (!Array.isArray(points)) - throw new Error("array expected"); - points.forEach((p, i) => { - if (!(p instanceof c)) - throw new Error("invalid point at index " + i); - }); -} -function validateMSMScalars(scalars, field) { - if (!Array.isArray(scalars)) - throw new Error("array of scalars expected"); - scalars.forEach((s, i) => { - if (!field.isValid(s)) - throw new Error("invalid scalar at index " + i); - }); -} -var pointPrecomputes = /* @__PURE__ */ new WeakMap(); -var pointWindowSizes = /* @__PURE__ */ new WeakMap(); -function getW(P) { - return pointWindowSizes.get(P) || 1; -} -function wNAF(c, bits) { - return { - constTimeNegate, - hasPrecomputes(elm) { - return getW(elm) !== 1; - }, - // non-const time multiplication ladder - unsafeLadder(elm, n, p = c.ZERO) { - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @param elm Point instance - * @param W window size - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W) { - const { windows, windowSize } = calcWOpts(W, bits); - const points = []; - let p = elm; - let base = p; - for (let window = 0; window < windows; window++) { - base = p; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - const { windows, windowSize } = calcWOpts(W, bits); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window = 0; window < windows; window++) { - const offset = window * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f }; - }, - /** - * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @param acc accumulator point to add result of multiplication - * @returns point - */ - wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { - const { windows, windowSize } = calcWOpts(W, bits); - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window = 0; window < windows; window++) { - const offset = window * windowSize; - if (n === _0n3) - break; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - if (wbits === 0) - continue; - let curr = precomputes[offset + Math.abs(wbits) - 1]; - if (wbits < 0) - curr = curr.negate(); - acc = acc.add(curr); - } - return acc; - }, - getPrecomputes(W, P, transform) { - let comp = pointPrecomputes.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) - pointPrecomputes.set(P, transform(comp)); - } - return comp; - }, - wNAFCached(P, n, transform) { - const W = getW(P); - return this.wNAF(W, this.getPrecomputes(W, P, transform), n); - }, - wNAFCachedUnsafe(P, n, transform, prev) { - const W = getW(P); - if (W === 1) - return this.unsafeLadder(P, n, prev); - return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); - }, - // We calculate precomputes for elliptic curve point multiplication - // using windowed method. This specifies window size and - // stores precomputed values. Usually only base point would be precomputed. - setWindowSize(P, W) { - validateW(W, bits); - pointWindowSizes.set(P, W); - pointPrecomputes.delete(P); - } - }; -} -function pippenger(c, fieldN, points, scalars) { - validateMSMPoints(points, c); - validateMSMScalars(scalars, fieldN); - if (points.length !== scalars.length) - throw new Error("arrays of points and scalars must have equal length"); - const zero = c.ZERO; - const wbits = bitLen(BigInt(points.length)); - const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; - const MASK = (1 << windowSize) - 1; - const buckets = new Array(MASK + 1).fill(zero); - const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; - let sum = zero; - for (let i = lastBits; i >= 0; i -= windowSize) { - buckets.fill(zero); - for (let j = 0; j < scalars.length; j++) { - const scalar = scalars[j]; - const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); - buckets[wbits2] = buckets[wbits2].add(points[j]); - } - let resI = zero; - for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { - sumI = sumI.add(buckets[j]); - resI = resI.add(sumI); - } - sum = sum.add(resI); - if (i !== 0) - for (let j = 0; j < windowSize; j++) - sum = sum.double(); - } - return sum; -} -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js -function validateSigVerOpts(opts) { - if (opts.lowS !== void 0) - abool("lowS", opts.lowS); - if (opts.prehash !== void 0) - abool("prehash", opts.prehash); -} -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp, a } = opts; - if (endo) { - if (!Fp.eql(a, Fp.ZERO)) { - throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function"); - } - } - return Object.freeze({ ...opts }); -} -var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; -var DER = { - // asn.1 DER encoding utils - Err: class DERErr extends Error { - constructor(m = "") { - super(m); - } - }, - // Basic building block is TLV (Tag-Length-Value) - _tlv: { - encode: (tag, data) => { - const { Err: E } = DER; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length & 1) - throw new E("tlv.encode: unpadded data"); - const dataLen = data.length / 2; - const len = numberToHexUnpadded(dataLen); - if (len.length / 2 & 128) - throw new E("tlv.encode: long form length too big"); - const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; - const t = numberToHexUnpadded(tag); - return t + lenLen + len + data; - }, - // v - value, l - left bytes (unparsed) - decode(tag, data) { - const { Err: E } = DER; - let pos = 0; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length < 2 || data[pos++] !== tag) - throw new E("tlv.decode: wrong tlv"); - const first = data[pos++]; - const isLong = !!(first & 128); - let length = 0; - if (!isLong) - length = first; - else { - const lenLen = first & 127; - if (!lenLen) - throw new E("tlv.decode(long): indefinite length not supported"); - if (lenLen > 4) - throw new E("tlv.decode(long): byte length is too big"); - const lengthBytes = data.subarray(pos, pos + lenLen); - if (lengthBytes.length !== lenLen) - throw new E("tlv.decode: length bytes not complete"); - if (lengthBytes[0] === 0) - throw new E("tlv.decode(long): zero leftmost byte"); - for (const b of lengthBytes) - length = length << 8 | b; - pos += lenLen; - if (length < 128) - throw new E("tlv.decode(long): not minimal encoding"); - } - const v = data.subarray(pos, pos + length); - if (v.length !== length) - throw new E("tlv.decode: wrong value length"); - return { v, l: data.subarray(pos + length) }; - } - }, - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - _int: { - encode(num2) { - const { Err: E } = DER; - if (num2 < _0n4) - throw new E("integer: negative integers are not allowed"); - let hex = numberToHexUnpadded(num2); - if (Number.parseInt(hex[0], 16) & 8) - hex = "00" + hex; - if (hex.length & 1) - throw new E("unexpected DER parsing assertion: unpadded hex"); - return hex; - }, - decode(data) { - const { Err: E } = DER; - if (data[0] & 128) - throw new E("invalid signature integer: negative"); - if (data[0] === 0 && !(data[1] & 128)) - throw new E("invalid signature integer: unnecessary leading zero"); - return b2n(data); - } - }, - toSig(hex) { - const { Err: E, _int: int, _tlv: tlv } = DER; - const data = typeof hex === "string" ? h2b(hex) : hex; - abytes2(data); - const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); - if (seqLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); - const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); - if (sLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - return { r: int.decode(rBytes), s: int.decode(sBytes) }; - }, - hexFromSig(sig) { - const { _tlv: tlv, _int: int } = DER; - const rs = tlv.encode(2, int.encode(sig.r)); - const ss = tlv.encode(2, int.encode(sig.s)); - const seq = rs + ss; - return tlv.encode(48, seq); - } -}; -var _0n4 = BigInt(0); -var _1n4 = BigInt(1); -var _2n3 = BigInt(2); -var _3n2 = BigInt(3); -var _4n2 = BigInt(4); -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp } = CURVE; - const Fn = Field(CURVE.n, CURVE.nBitLength); - const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes2(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes) => { - const tail = bytes.subarray(1); - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp.sqr(x); - const x3 = Fp.mul(x2, x); - return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); - } - if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num2) { - return inRange(num2, _1n4, CURVE.n); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; - if (lengths && typeof key !== "bigint") { - if (isBytes2(key)) - key = bytesToHex(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("invalid private key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num2; - try { - num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); - } - if (wrapPrivateKey) - num2 = mod(num2, N); - aInRange("private key", num2, _1n4, N); - return num2; - } - function assertPrjPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ProjectivePoint expected"); - } - const toAffineMemo = memoized((p, iz) => { - const { px: x, py: y, pz: z } = p; - if (Fp.eql(z, Fp.ONE)) - return { x, y }; - const is0 = p.is0(); - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(z); - const ax = Fp.mul(x, iz); - const ay = Fp.mul(y, iz); - const zz = Fp.mul(z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - }); - const assertValidMemo = memoized((p) => { - if (p.is0()) { - if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = p.toAffine(); - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("bad point: x or y not FE"); - const left = Fp.sqr(y); - const right = weierstrassEquation(x); - if (!Fp.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!p.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - return true; - }); - class Point2 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp.isValid(pz)) - throw new Error("z required"); - Object.freeze(this); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point2) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp.eql(i, Fp.ZERO); - if (is0(x) && is0(y)) - return Point2.ZERO; - return new Point2(x, y, Fp.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex) { - const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex))); - P.assertValidity(); - return P; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // Multiscalar Multiplication - static msm(points, scalars) { - return pippenger(Point2, Fn, points, scalars); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - wnaf.setWindowSize(this, windowSize); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - assertValidMemo(this); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp.isOdd) - return !Fp.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point2(this.px, Fp.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - let t0 = Fp.mul(X1, X1); - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); - Z3 = Fp.add(Z3, Z3); - return new Point2(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n2); - let t0 = Fp.mul(X1, X2); - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); - return new Point2(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point2.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, n, Point2.normalizeZ); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(sc) { - const { endo, n: N } = CURVE; - aInRange("scalar", sc, _0n4, N); - const I = Point2.ZERO; - if (sc === _0n4) - return I; - if (this.is0() || sc === _1n4) - return this; - if (!endo || wnaf.hasPrecomputes(this)) - return wnaf.wNAFCachedUnsafe(this, sc, Point2.normalizeZ); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n4 || k2 > _0n4) { - if (k1 & _1n4) - k1p = k1p.add(d); - if (k2 & _1n4) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n4; - k2 >>= _1n4; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - const { endo, n: N } = CURVE; - aInRange("scalar", scalar, _1n4, N); - let point, fake; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(scalar); - point = p; - fake = f; - } - return Point2.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q, a, b) { - const G = Point2.BASE; - const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? void 0 : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - return toAffineMemo(this, iz); - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - abool("isCompressed", isCompressed); - this.assertValidity(); - return toBytes2(Point2, this, isCompressed); - } - toHex(isCompressed = true) { - abool("isCompressed", isCompressed); - return bytesToHex(this.toRawBytes(isCompressed)); - } - } - Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp.ONE); - Point2.ZERO = new Point2(Fp.ZERO, Fp.ONE, Fp.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point2, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; -} -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); -} -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp.BYTES + 1; - const uncompressedLen = 2 * Fp.BYTES + 1; - function modN2(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp.toBytes(a.x); - const cat = concatBytes2; - abool("isCompressed", isCompressed); - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y)); - } - }, - fromBytes(bytes) { - const len = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!inRange(x, _1n4, Fp.ORDER)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y; - try { - y = Fp.sqrt(y2); - } catch (sqrtError) { - const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("Point is not on curve" + suffix); - } - const isYOdd = (y & _1n4) === _1n4; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - } else { - const cl = compressedLen; - const ul = uncompressedLen; - throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len); - } - } - }); - const numToNByteStr = (num2) => bytesToHex(numberToBytesBE(num2, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n4; - return number > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; - } - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex) { - const l = CURVE.nByteLength; - hex = ensureBytes("compactSignature", hex, l * 2); - return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex) { - const { r, s } = DER.toSig(ensureBytes("DER", hex)); - return new Signature(r, s); - } - assertValidity() { - aInRange("r", this.r, _1n4, CURVE_ORDER); - aInRange("s", this.s, _1n4, CURVE_ORDER); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point2.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN2(-h * ir); - const u2 = modN2(s * ir); - const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point2.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey(privateKey, isCompressed = true) { - return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = isBytes2(item); - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b = Point2.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes) { - if (bytes.length > 8192) - throw new Error("input is too large"); - const num2 = bytesToNumberBE(bytes); - const delta = bytes.length * 8 - CURVE.nBitLength; - return delta > 0 ? num2 >> BigInt(delta) : num2; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes) { - return modN2(bits2int(bytes)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num2) { - aInRange("num < 2^" + CURVE.nBitLength, num2, _0n4, ORDER_MASK); - return numberToBytesBE(num2, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { hash, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - validateSigVerOpts(opts); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null && ent !== false) { - const e = ent === true ? randomBytes2(Fp.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); - } - const seed = concatBytes2(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point2.BASE.multiply(k).toAffine(); - const r = modN2(q.x); - if (r === _0n4) - return; - const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point2.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - const { lowS, prehash, format } = opts; - validateSigVerOpts(opts); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - if (format !== void 0 && format !== "compact" && format !== "der") - throw new Error("format must be compact or der"); - const isHex = typeof sg === "string" || isBytes2(sg); - const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; - if (!isHex && !isObj) - throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); - let _sig = void 0; - let P; - try { - if (isObj) - _sig = new Signature(sg.r, sg.s); - if (isHex) { - try { - if (format !== "compact") - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - } - if (!_sig && format !== "der") - _sig = Signature.fromCompact(sg); - } - P = Point2.fromHex(publicKey); - } catch (error) { - return false; - } - if (!_sig) - return false; - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN2(h * is); - const u2 = modN2(r * is); - const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); - if (!R) - return false; - const v = modN2(R.x); - return v === r; - } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point2, - Signature, - utils - }; -} -function SWUFpSqrtRatio(Fp, Z) { - const q = Fp.ORDER; - let l = _0n4; - for (let o = q - _1n4; o % _2n3 === _0n4; o /= _2n3) - l += _1n4; - const c1 = l; - const _2n_pow_c1_1 = _2n3 << c1 - _1n4 - _1n4; - const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; - const c2 = (q - _1n4) / _2n_pow_c1; - const c3 = (c2 - _1n4) / _2n3; - const c4 = _2n_pow_c1 - _1n4; - const c5 = _2n_pow_c1_1; - const c6 = Fp.pow(Z, c2); - const c7 = Fp.pow(Z, (c2 + _1n4) / _2n3); - let sqrtRatio = (u, v) => { - let tv1 = c6; - let tv2 = Fp.pow(v, c4); - let tv3 = Fp.sqr(tv2); - tv3 = Fp.mul(tv3, v); - let tv5 = Fp.mul(u, tv3); - tv5 = Fp.pow(tv5, c3); - tv5 = Fp.mul(tv5, tv2); - tv2 = Fp.mul(tv5, v); - tv3 = Fp.mul(tv5, u); - let tv4 = Fp.mul(tv3, tv2); - tv5 = Fp.pow(tv4, c5); - let isQR = Fp.eql(tv5, Fp.ONE); - tv2 = Fp.mul(tv3, c7); - tv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, isQR); - tv4 = Fp.cmov(tv5, tv4, isQR); - for (let i = c1; i > _1n4; i--) { - let tv52 = i - _2n3; - tv52 = _2n3 << tv52 - _1n4; - let tvv5 = Fp.pow(tv4, tv52); - const e1 = Fp.eql(tvv5, Fp.ONE); - tv2 = Fp.mul(tv3, tv1); - tv1 = Fp.mul(tv1, tv1); - tvv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, e1); - tv4 = Fp.cmov(tvv5, tv4, e1); - } - return { isValid: isQR, value: tv3 }; - }; - if (Fp.ORDER % _4n2 === _3n2) { - const c12 = (Fp.ORDER - _3n2) / _4n2; - const c22 = Fp.sqrt(Fp.neg(Z)); - sqrtRatio = (u, v) => { - let tv1 = Fp.sqr(v); - const tv2 = Fp.mul(u, v); - tv1 = Fp.mul(tv1, tv2); - let y1 = Fp.pow(tv1, c12); - y1 = Fp.mul(y1, tv2); - const y2 = Fp.mul(y1, c22); - const tv3 = Fp.mul(Fp.sqr(y1), v); - const isQR = Fp.eql(tv3, u); - let y = Fp.cmov(y2, y1, isQR); - return { isValid: isQR, value: y }; - }; - } - return sqrtRatio; -} -function mapToCurveSimpleSWU(Fp, opts) { - validateField(Fp); - if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) - throw new Error("mapToCurveSimpleSWU: invalid opts"); - const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); - if (!Fp.isOdd) - throw new Error("Fp.isOdd is not implemented!"); - return (u) => { - let tv1, tv2, tv3, tv4, tv5, tv6, x, y; - tv1 = Fp.sqr(u); - tv1 = Fp.mul(tv1, opts.Z); - tv2 = Fp.sqr(tv1); - tv2 = Fp.add(tv2, tv1); - tv3 = Fp.add(tv2, Fp.ONE); - tv3 = Fp.mul(tv3, opts.B); - tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); - tv4 = Fp.mul(tv4, opts.A); - tv2 = Fp.sqr(tv3); - tv6 = Fp.sqr(tv4); - tv5 = Fp.mul(tv6, opts.A); - tv2 = Fp.add(tv2, tv5); - tv2 = Fp.mul(tv2, tv3); - tv6 = Fp.mul(tv6, tv4); - tv5 = Fp.mul(tv6, opts.B); - tv2 = Fp.add(tv2, tv5); - x = Fp.mul(tv1, tv3); - const { isValid, value } = sqrtRatio(tv2, tv6); - y = Fp.mul(tv1, u); - y = Fp.mul(y, value); - x = Fp.cmov(x, tv3, isValid); - y = Fp.cmov(y, value, isValid); - const e1 = Fp.isOdd(u) === Fp.isOdd(y); - y = Fp.cmov(Fp.neg(y), y, e1); - x = Fp.div(x, tv4); - return { x, y }; - }; -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js -function getHash(hash) { - return { - hash, - hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)), - randomBytes - }; -} -function createCurve(curveDef, defHash) { - const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); - return Object.freeze({ ...create(defHash), create }); -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js -var os2ip = bytesToNumberBE; -function i2osp(value, length) { - anum(value); - anum(length); - if (value < 0 || value >= 1 << 8 * length) - throw new Error("invalid I2OSP input: " + value); - const res = Array.from({ length }).fill(0); - for (let i = length - 1; i >= 0; i--) { - res[i] = value & 255; - value >>>= 8; - } - return new Uint8Array(res); -} -function strxor(a, b) { - const arr = new Uint8Array(a.length); - for (let i = 0; i < a.length; i++) { - arr[i] = a[i] ^ b[i]; - } - return arr; -} -function anum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); -} -function expand_message_xmd(msg, DST, lenInBytes, H) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) - DST = H(concatBytes2(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); - const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; - const ell = Math.ceil(lenInBytes / b_in_bytes); - if (lenInBytes > 65535 || ell > 255) - throw new Error("expand_message_xmd: invalid lenInBytes"); - const DST_prime = concatBytes2(DST, i2osp(DST.length, 1)); - const Z_pad = i2osp(0, r_in_bytes); - const l_i_b_str = i2osp(lenInBytes, 2); - const b = new Array(ell); - const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); - b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime)); - for (let i = 1; i <= ell; i++) { - const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; - b[i] = H(concatBytes2(...args)); - } - const pseudo_random_bytes = concatBytes2(...b); - return pseudo_random_bytes.slice(0, lenInBytes); -} -function expand_message_xof(msg, DST, lenInBytes, k, H) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) { - const dkLen = Math.ceil(2 * k / 8); - DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); - } - if (lenInBytes > 65535 || DST.length > 255) - throw new Error("expand_message_xof: invalid lenInBytes"); - return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); -} -function hash_to_field(msg, count, options) { - validateObject(options, { - DST: "stringOrUint8Array", - p: "bigint", - m: "isSafeInteger", - k: "isSafeInteger", - hash: "hash" - }); - const { p, k, m, hash, expand, DST: _DST } = options; - abytes2(msg); - anum(count); - const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; - const log2p = p.toString(2).length; - const L = Math.ceil((log2p + k) / 8); - const len_in_bytes = count * m * L; - let prb; - if (expand === "xmd") { - prb = expand_message_xmd(msg, DST, len_in_bytes, hash); - } else if (expand === "xof") { - prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); - } else if (expand === "_internal_pass") { - prb = msg; - } else { - throw new Error('expand must be "xmd" or "xof"'); - } - const u = new Array(count); - for (let i = 0; i < count; i++) { - const e = new Array(m); - for (let j = 0; j < m; j++) { - const elm_offset = L * (j + i * m); - const tv = prb.subarray(elm_offset, elm_offset + L); - e[j] = mod(os2ip(tv), p); - } - u[i] = e; - } - return u; -} -function isogenyMap(field, map) { - const COEFF = map.map((i) => Array.from(i).reverse()); - return (x, y) => { - const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); - x = field.div(xNum, xDen); - y = field.mul(y, field.div(yNum, yDen)); - return { x, y }; - }; -} -function createHasher(Point2, mapToCurve, def) { - if (typeof mapToCurve !== "function") - throw new Error("mapToCurve() must be defined"); - return { - // Encodes byte string to elliptic curve. - // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - hashToCurve(msg, options) { - const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); - const u0 = Point2.fromAffine(mapToCurve(u[0])); - const u1 = Point2.fromAffine(mapToCurve(u[1])); - const P = u0.add(u1).clearCofactor(); - P.assertValidity(); - return P; - }, - // Encodes byte string to elliptic curve. - // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - encodeToCurve(msg, options) { - const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); - const P = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); - P.assertValidity(); - return P; - }, - // Same as encodeToCurve, but without hash - mapToCurve(scalars) { - if (!Array.isArray(scalars)) - throw new Error("mapToCurve: expected array of bigints"); - for (const i of scalars) - if (typeof i !== "bigint") - throw new Error("mapToCurve: expected array of bigints"); - const P = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); - P.assertValidity(); - return P; - } - }; -} - -// ../../node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js -var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); -var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -var _1n5 = BigInt(1); -var _2n4 = BigInt(2); -var divNearest = (a, b) => (a + b / _2n4) / b; -function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fpk1.eql(Fpk1.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; -} -var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); -var secp256k1 = createCurve({ - a: BigInt(0), - // equation params: a, b - b: BigInt(7), - // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 - Fp: Fpk1, - // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n - n: secp256k1N, - // Curve order, total count of valid points in the field - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - // Cofactor - lowS: true, - // Allow only low-S signatures by default in sign() and verify() - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } -}, sha256); -var _0n5 = BigInt(0); -var TAGGED_HASH_PREFIXES = {}; -function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes2(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes2(tagP, ...messages)); -} -var pointToBytes = (point) => point.toRawBytes(true).slice(1); -var numTo32b = (n) => numberToBytesBE(n, 32); -var modP = (x) => mod(x, secp256k1P); -var modN = (x) => mod(x, secp256k1N); -var Point = secp256k1.ProjectivePoint; -var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); -function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; -} -function lift_x(x) { - aInRange("x", x, _1n5, secp256k1P); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); - const p = new Point(x, y, _1n5); - p.assertValidity(); - return p; -} -var num = bytesToNumberBE; -function challenge(...args) { - return modN(num(taggedHash("BIP0340/challenge", ...args))); -} -function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; -} -function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(num(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; -} -function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P = lift_x(num(pub)); - const r = num(sig.subarray(0, 32)); - if (!inRange(r, _1n5, secp256k1P)) - return false; - const s = num(sig.subarray(32, 64)); - if (!inRange(s, _1n5, secp256k1N)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; - } -} -var schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } -}))(); -var isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ - // xNum - [ - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", - "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", - "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" - ], - // xDen - [ - "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", - "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ], - // yNum - [ - "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", - "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", - "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", - "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" - ], - // yDen - [ - "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", - "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", - "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ] -].map((i) => i.map((j) => BigInt(j)))))(); -var mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { - A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), - B: BigInt("1771"), - Z: Fpk1.create(BigInt("-11")) -}))(); -var htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { - const { x, y } = mapSWU(Fpk1.create(scalars[0])); - return isoMap(x, y); -}, { - DST: "secp256k1_XMD:SHA-256_SSWU_RO_", - encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", - p: Fpk1.ORDER, - m: 1, - k: 128, - expand: "xmd", - hash: sha256 -}))(); -var hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); -var encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); - -export { - secp256k1, - schnorr, - hashToCurve, - encodeToCurve -}; -/*! Bundled license information: - -@noble/hashes/esm/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/modular.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/curve.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/weierstrass.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/_shortw_utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/secp256k1.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=chunk-4L6P6TY5.js.map \ No newline at end of file diff --git a/dist/chunk-4L6P6TY5.js.map b/dist/chunk-4L6P6TY5.js.map deleted file mode 100644 index c93a5cf..0000000 --- a/dist/chunk-4L6P6TY5.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../node_modules/viem/node_modules/@noble/curves/src/_shortw_utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/secp256k1.ts"],"sourcesContent":["function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n// Falls back to Node.js built-in crypto for Node.js <=v14\n// See utils.ts for details.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { ahash, abytes, aexists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\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('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn: (arg: T, ...args: O) => R) {\n const map = new WeakMap();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n =/* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000) throw new Error('Cannot find square root: likely non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\nexport function FpLegendre(order: bigint) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f: IField, x: T): T => f.pow(x, legendreConst);\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendre = FpLegendre(f.ORDER);\n return (x: T): boolean => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType; // cached sqrtP\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\nfunction constTimeNegate>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\nfunction calcWOpts(W: number, bits: number) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n) break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0) continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0) curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger>(\n c: GroupConstructor,\n fieldN: IField,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe>(\n c: GroupConstructor,\n fieldN: IField,\n points: T[],\n windowSize: number\n) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = BigInt((1 << windowSize) - 1);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport {\n AffinePoint,\n BasicCurve,\n Group,\n GroupConstructor,\n validateBasic,\n wNAF,\n pippenger,\n} from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes, memoized, abool } from './utils.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n msm(points: ProjPointType[], scalars: bigint[]): ProjPointType;\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n CURVE: ReturnType>;\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = ut.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint) {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType): CurvePointsRes {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // Our custom check \"just in case\"\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n ut.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || ut.isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { CHash } from './abstract/utils.js';\nimport { CurveType, weierstrass } from './abstract/weierstrass.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.js';\nimport { IField, mod } from './modular.js';\nimport type { CHash } from './utils.js';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js';\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\ntype UnicodeOrBytes = string | Uint8Array;\nexport type Opts = {\n DST: UnicodeOrBytes;\n p: bigint;\n m: number;\n k: number;\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction anum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\n// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n// Produces a uniformly random byte string using an extendable-output function (XOF) H.\n// 1. The collision resistance of H MUST be at least k bits.\n// 2. H MUST be an XOF that has been proved indifferentiable from\n// a random oracle under a reasonable cryptographic assumption.\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\n * https://www.rfc-editor.org/rfc/rfc9380#section-5.2\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n abytes(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\nexport interface H2CPoint extends Group> {\n add(rhs: H2CPoint): H2CPoint;\n toAffine(iz?: bigint): AffinePoint;\n clearCofactor(): H2CPoint;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor extends GroupConstructor> {\n fromAffine(ap: AffinePoint): H2CPoint;\n}\n\nexport type MapToCurve = (scalar: bigint[]) => AffinePoint;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\n\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n def: Opts & { encodeDST?: UnicodeOrBytes }\n) {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts);\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts);\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]) {\n if (!Array.isArray(scalars)) throw new Error('mapToCurve: expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('mapToCurve: expected array of bigints');\n const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport {\n inRange,\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n numberToBytesBE,\n} from './abstract/utils.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,GAAS;AACxB,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI;AAAG,UAAM,IAAI,MAAM,oCAAoC,CAAC;AAC9F;AAGA,SAAS,QAAQ,GAAU;AACzB,SAAO,aAAa,cAAe,YAAY,OAAO,CAAC,KAAK,EAAE,YAAY,SAAS;AACrF;AAEA,SAAS,OAAO,MAA8B,SAAiB;AAC7D,MAAI,CAAC,QAAQ,CAAC;AAAG,UAAM,IAAI,MAAM,qBAAqB;AAC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;IACE;IACA;IACA;IACA;;;EAGF;IACE;IACA;IACA;IACA;;;EAEF,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,CAA6C,GACjF;AACJ,IAAM,SAA0B,uBAC9B,oBAAoB,MAAM;EACxB,GAAG,OAAO,oEAAoE;EAC9E,GAAG,OAAO,MAAM;EAChB,GAAG,KAAK,OAAO,OAAO,KAAK,CAAC;CAC7B,GAAE;AACL,IAAM,MAAuB,uBAC3B,aACE,UAAU,iBACV,CAAC,YAAqB;AACpB,QAAM,EAAE,GAAG,EAAC,IAAK,OAAO,KAAK,OAAO,QAAQ,CAAC,CAAC,CAAC;AAC/C,SAAO,OAAO,GAAG,CAAC;AACpB,GACA;EACE,KAAK;EACL,WAAW;EACX,GAAG,KAAK;EACR,GAAG;EACH,GAAG;EACH,QAAQ;EACR,MAAM;CACP,GACD;AACG,IAAM,cAA+B,uBAAM,IAAI,aAAY;AAC3D,IAAM,gBAAiC,uBAAM,IAAI,eAAc;","names":["abytes","concatBytes","isBytes","utf8ToBytes","num","_0n","_1n","_2n","num","num","_0n","_1n","bitLen","_0n","_1n","num","num","_1n","_0n","_1n","wbits","num","_0n","abytes","_1n","_2n","_3n","_4n","toBytes","concatBytes","isBytes","Point","a","modN","randomBytes","tv5","c1","c2","abytes","concatBytes","utf8ToBytes","Point","_1n","_2n","_3n","_0n","concatBytes"]} \ No newline at end of file diff --git a/dist/chunk-NTU6R7BC.js b/dist/chunk-NTU6R7BC.js deleted file mode 100644 index 25786aa..0000000 --- a/dist/chunk-NTU6R7BC.js +++ /dev/null @@ -1,4019 +0,0 @@ -// ../../node_modules/viem/node_modules/abitype/dist/esm/version.js -var version = "1.0.7"; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/errors.js -var BaseError = class _BaseError extends Error { - constructor(shortMessage, args = {}) { - const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; - const docsPath4 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath; - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsPath4 ? [`Docs: https://abitype.dev${docsPath4}`] : [], - ...details ? [`Details: ${details}`] : [], - `Version: abitype@${version}` - ].join("\n"); - super(message); - 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: "AbiTypeError" - }); - if (args.cause) - this.cause = args.cause; - this.details = details; - this.docsPath = docsPath4; - this.metaMessages = args.metaMessages; - this.shortMessage = shortMessage; - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/regex.js -function execTyped(regex, string) { - const match = regex.exec(string); - return match?.groups; -} -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)?$/; -var isTupleRegex = /^\(.+?\).*?$/; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js -var tupleRegex = /^tuple(?(\[(\d*)\])*)$/; -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 - }); - } - if ("indexed" in abiParameter && abiParameter.indexed) - type = `${type} indexed`; - if (abiParameter.name) - return `${type} ${abiParameter.name}`; - return type; -} - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js -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; -} - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/formatAbiItem.js -function formatAbiItem(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)})` : ""}`; - if (abiItem.type === "event") - return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "error") - return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "constructor") - return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; - if (abiItem.type === "fallback") - return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; - return "receive() external payable"; -} - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/signatures.js -var errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; -function isErrorSignature(signature) { - return errorSignatureRegex.test(signature); -} -function execErrorSignature(signature) { - return execTyped(errorSignatureRegex, signature); -} -var eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; -function isEventSignature(signature) { - return eventSignatureRegex.test(signature); -} -function execEventSignature(signature) { - return execTyped(eventSignatureRegex, signature); -} -var functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; -function isFunctionSignature(signature) { - return functionSignatureRegex.test(signature); -} -function execFunctionSignature(signature) { - return execTyped(functionSignatureRegex, signature); -} -var structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; -function isStructSignature(signature) { - return structSignatureRegex.test(signature); -} -function execStructSignature(signature) { - return execTyped(structSignatureRegex, signature); -} -var constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; -function isConstructorSignature(signature) { - return constructorSignatureRegex.test(signature); -} -function execConstructorSignature(signature) { - return execTyped(constructorSignatureRegex, signature); -} -var fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; -function isFallbackSignature(signature) { - return fallbackSignatureRegex.test(signature); -} -var receiveSignatureRegex = /^receive\(\) external payable$/; -function isReceiveSignature(signature) { - return receiveSignatureRegex.test(signature); -} -var eventModifiers = /* @__PURE__ */ new Set(["indexed"]); -var functionModifiers = /* @__PURE__ */ new Set([ - "calldata", - "memory", - "storage" -]); - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/abiItem.js -var UnknownTypeError = class extends BaseError { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [ - `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownTypeError" - }); - } -}; -var UnknownSolidityTypeError = class extends BaseError { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [`Type "${type}" is not a valid ABI type.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSolidityTypeError" - }); - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js -var InvalidParameterError = class extends BaseError { - constructor({ param }) { - super("Invalid ABI parameter.", { - details: param - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParameterError" - }); - } -}; -var SolidityProtectedKeywordError = class extends BaseError { - constructor({ param, name }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "SolidityProtectedKeywordError" - }); - } -}; -var InvalidModifierError = class extends BaseError { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidModifierError" - }); - } -}; -var InvalidFunctionModifierError = class extends BaseError { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, - `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidFunctionModifierError" - }); - } -}; -var InvalidAbiTypeParameterError = class extends BaseError { - constructor({ abiParameter }) { - super("Invalid ABI parameter.", { - details: JSON.stringify(abiParameter, null, 2), - metaMessages: ["ABI parameter type is invalid."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidAbiTypeParameterError" - }); - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/signature.js -var InvalidSignatureError = class extends BaseError { - constructor({ signature, type }) { - super(`Invalid ${type} signature.`, { - details: signature - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidSignatureError" - }); - } -}; -var UnknownSignatureError = class extends BaseError { - constructor({ signature }) { - super("Unknown signature.", { - details: signature - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSignatureError" - }); - } -}; -var InvalidStructSignatureError = class extends BaseError { - constructor({ signature }) { - super("Invalid struct signature.", { - details: signature, - metaMessages: ["No properties exist."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidStructSignatureError" - }); - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/struct.js -var CircularReferenceError = class extends BaseError { - constructor({ type }) { - super("Circular reference detected.", { - metaMessages: [`Struct "${type}" is a circular reference.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "CircularReferenceError" - }); - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js -var InvalidParenthesisError = class extends BaseError { - constructor({ current, depth }) { - super("Unbalanced parentheses.", { - metaMessages: [ - `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` - ], - details: `Depth "${depth}"` - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParenthesisError" - }); - } -}; - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/cache.js -function getParameterCacheKey(param, type, structs) { - let structKey = ""; - if (structs) - for (const struct of Object.entries(structs)) { - if (!struct) - continue; - let propertyKey = ""; - for (const property of struct[1]) { - propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`; - } - structKey += `(${struct[0]}{${propertyKey}})`; - } - if (type) - return `${type}:${param}${structKey}`; - return param; -} -var parameterCache = /* @__PURE__ */ new Map([ - // Unnamed - ["address", { type: "address" }], - ["bool", { type: "bool" }], - ["bytes", { type: "bytes" }], - ["bytes32", { type: "bytes32" }], - ["int", { type: "int256" }], - ["int256", { type: "int256" }], - ["string", { type: "string" }], - ["uint", { type: "uint256" }], - ["uint8", { type: "uint8" }], - ["uint16", { type: "uint16" }], - ["uint24", { type: "uint24" }], - ["uint32", { type: "uint32" }], - ["uint64", { type: "uint64" }], - ["uint96", { type: "uint96" }], - ["uint112", { type: "uint112" }], - ["uint160", { type: "uint160" }], - ["uint192", { type: "uint192" }], - ["uint256", { type: "uint256" }], - // Named - ["address owner", { type: "address", name: "owner" }], - ["address to", { type: "address", name: "to" }], - ["bool approved", { type: "bool", name: "approved" }], - ["bytes _data", { type: "bytes", name: "_data" }], - ["bytes data", { type: "bytes", name: "data" }], - ["bytes signature", { type: "bytes", name: "signature" }], - ["bytes32 hash", { type: "bytes32", name: "hash" }], - ["bytes32 r", { type: "bytes32", name: "r" }], - ["bytes32 root", { type: "bytes32", name: "root" }], - ["bytes32 s", { type: "bytes32", name: "s" }], - ["string name", { type: "string", name: "name" }], - ["string symbol", { type: "string", name: "symbol" }], - ["string tokenURI", { type: "string", name: "tokenURI" }], - ["uint tokenId", { type: "uint256", name: "tokenId" }], - ["uint8 v", { type: "uint8", name: "v" }], - ["uint256 balance", { type: "uint256", name: "balance" }], - ["uint256 tokenId", { type: "uint256", name: "tokenId" }], - ["uint256 value", { type: "uint256", name: "value" }], - // Indexed - [ - "event:address indexed from", - { type: "address", name: "from", indexed: true } - ], - ["event:address indexed to", { type: "address", name: "to", indexed: true }], - [ - "event:uint indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ], - [ - "event:uint256 indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ] -]); - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/utils.js -function parseSignature(signature, structs = {}) { - if (isFunctionSignature(signature)) { - const match = execFunctionSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "function" }); - const inputParams = splitParameters(match.parameters); - const inputs = []; - const inputLength = inputParams.length; - for (let i = 0; i < inputLength; i++) { - inputs.push(parseAbiParameter(inputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - const outputs = []; - if (match.returns) { - const outputParams = splitParameters(match.returns); - const outputLength = outputParams.length; - for (let i = 0; i < outputLength; i++) { - outputs.push(parseAbiParameter(outputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - } - return { - name: match.name, - type: "function", - stateMutability: match.stateMutability ?? "nonpayable", - inputs, - outputs - }; - } - if (isEventSignature(signature)) { - const match = execEventSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "event" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { - modifiers: eventModifiers, - structs, - type: "event" - })); - } - return { name: match.name, type: "event", inputs: abiParameters }; - } - if (isErrorSignature(signature)) { - const match = execErrorSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "error" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); - } - return { name: match.name, type: "error", inputs: abiParameters }; - } - if (isConstructorSignature(signature)) { - const match = execConstructorSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "constructor" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); - } - return { - type: "constructor", - stateMutability: match.stateMutability ?? "nonpayable", - inputs: abiParameters - }; - } - if (isFallbackSignature(signature)) - return { type: "fallback" }; - if (isReceiveSignature(signature)) - return { - type: "receive", - stateMutability: "payable" - }; - throw new UnknownSignatureError({ signature }); -} -var abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; -var abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; -var dynamicIntegerRegex = /^u?int$/; -function parseAbiParameter(param, options) { - const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs); - if (parameterCache.has(parameterCacheKey)) - return parameterCache.get(parameterCacheKey); - const isTuple = isTupleRegex.test(param); - const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); - if (!match) - throw new InvalidParameterError({ param }); - if (match.name && isSolidityKeyword(match.name)) - throw new SolidityProtectedKeywordError({ param, name: match.name }); - const name = match.name ? { name: match.name } : {}; - const indexed = match.modifier === "indexed" ? { indexed: true } : {}; - const structs = options?.structs ?? {}; - let type; - let components = {}; - if (isTuple) { - type = "tuple"; - const params = splitParameters(match.type); - const components_ = []; - const length = params.length; - for (let i = 0; i < length; i++) { - components_.push(parseAbiParameter(params[i], { structs })); - } - components = { components: components_ }; - } else if (match.type in structs) { - type = "tuple"; - components = { components: structs[match.type] }; - } else if (dynamicIntegerRegex.test(match.type)) { - type = `${match.type}256`; - } else { - type = match.type; - if (!(options?.type === "struct") && !isSolidityType(type)) - throw new UnknownSolidityTypeError({ type }); - } - if (match.modifier) { - if (!options?.modifiers?.has?.(match.modifier)) - throw new InvalidModifierError({ - param, - type: options?.type, - modifier: match.modifier - }); - if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) - throw new InvalidFunctionModifierError({ - param, - type: options?.type, - modifier: match.modifier - }); - } - const abiParameter = { - type: `${type}${match.array ?? ""}`, - ...name, - ...indexed, - ...components - }; - parameterCache.set(parameterCacheKey, abiParameter); - return abiParameter; -} -function splitParameters(params, result = [], current = "", depth = 0) { - const length = params.trim().length; - for (let i = 0; i < length; i++) { - const char = params[i]; - const tail = params.slice(i + 1); - switch (char) { - case ",": - return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); - case "(": - return splitParameters(tail, result, `${current}${char}`, depth + 1); - case ")": - return splitParameters(tail, result, `${current}${char}`, depth - 1); - default: - return splitParameters(tail, result, `${current}${char}`, depth); - } - } - if (current === "") - return result; - if (depth !== 0) - throw new InvalidParenthesisError({ current, depth }); - result.push(current.trim()); - return result; -} -function isSolidityType(type) { - return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type); -} -var protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; -function isSolidityKeyword(name) { - return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name); -} -function isValidDataLocation(type, isArray) { - return isArray || type === "bytes" || type === "string" || type === "tuple"; -} - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/runtime/structs.js -function parseStructs(signatures) { - const shallowStructs = {}; - const signaturesLength = signatures.length; - for (let i = 0; i < signaturesLength; i++) { - const signature = signatures[i]; - if (!isStructSignature(signature)) - continue; - const match = execStructSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "struct" }); - const properties = match.properties.split(";"); - const components = []; - const propertiesLength = properties.length; - for (let k = 0; k < propertiesLength; k++) { - const property = properties[k]; - const trimmed = property.trim(); - if (!trimmed) - continue; - const abiParameter = parseAbiParameter(trimmed, { - type: "struct" - }); - components.push(abiParameter); - } - if (!components.length) - throw new InvalidStructSignatureError({ signature }); - shallowStructs[match.name] = components; - } - const resolvedStructs = {}; - const entries = Object.entries(shallowStructs); - const entriesLength = entries.length; - for (let i = 0; i < entriesLength; i++) { - const [name, parameters] = entries[i]; - resolvedStructs[name] = resolveStructs(parameters, shallowStructs); - } - return resolvedStructs; -} -var typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; -function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { - const components = []; - const length = abiParameters.length; - for (let i = 0; i < length; i++) { - const abiParameter = abiParameters[i]; - const isTuple = isTupleRegex.test(abiParameter.type); - if (isTuple) - components.push(abiParameter); - else { - const match = execTyped(typeWithoutTupleRegex, abiParameter.type); - if (!match?.type) - throw new InvalidAbiTypeParameterError({ abiParameter }); - const { array, type } = match; - if (type in structs) { - if (ancestors.has(type)) - throw new CircularReferenceError({ type }); - components.push({ - ...abiParameter, - type: `tuple${array ?? ""}`, - components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) - }); - } else { - if (isSolidityType(type)) - components.push(abiParameter); - else - throw new UnknownTypeError({ type }); - } - } - } - return components; -} - -// ../../node_modules/viem/node_modules/abitype/dist/esm/human-readable/parseAbi.js -function parseAbi(signatures) { - const structs = parseStructs(signatures); - const abi = []; - const length = signatures.length; - for (let i = 0; i < length; i++) { - const signature = signatures[i]; - if (isStructSignature(signature)) - continue; - abi.push(parseSignature(signature, structs)); - } - return abi; -} - -// ../../node_modules/viem/_esm/accounts/utils/parseAccount.js -function parseAccount(account) { - if (typeof account === "string") - return { address: account, type: "json-rpc" }; - return account; -} - -// ../../node_modules/viem/_esm/constants/abis.js -var multicall3Abi = [ - { - inputs: [ - { - components: [ - { - name: "target", - type: "address" - }, - { - name: "allowFailure", - type: "bool" - }, - { - name: "callData", - type: "bytes" - } - ], - name: "calls", - type: "tuple[]" - } - ], - name: "aggregate3", - outputs: [ - { - components: [ - { - name: "success", - type: "bool" - }, - { - name: "returnData", - type: "bytes" - } - ], - name: "returnData", - type: "tuple[]" - } - ], - stateMutability: "view", - type: "function" - } -]; -var universalResolverErrors = [ - { - inputs: [], - name: "ResolverNotFound", - type: "error" - }, - { - inputs: [], - name: "ResolverWildcardNotSupported", - type: "error" - }, - { - inputs: [], - name: "ResolverNotContract", - type: "error" - }, - { - inputs: [ - { - name: "returnData", - type: "bytes" - } - ], - name: "ResolverError", - type: "error" - }, - { - inputs: [ - { - components: [ - { - name: "status", - type: "uint16" - }, - { - name: "message", - type: "string" - } - ], - name: "errors", - type: "tuple[]" - } - ], - name: "HttpError", - type: "error" - } -]; -var universalResolverResolveAbi = [ - ...universalResolverErrors, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] - }, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" }, - { name: "gateways", type: "string[]" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] - } -]; -var universalResolverReverseAbi = [ - ...universalResolverErrors, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [{ type: "bytes", name: "reverseName" }], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] - }, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [ - { type: "bytes", name: "reverseName" }, - { type: "string[]", name: "gateways" } - ], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] - } -]; - -// ../../node_modules/viem/_esm/constants/contract.js -var aggregate3Signature = "0x82ad56cb"; - -// ../../node_modules/viem/_esm/constants/contracts.js -var deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; -var deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; - -// ../../node_modules/viem/_esm/errors/version.js -var version2 = "2.21.58"; - -// ../../node_modules/viem/_esm/errors/base.js -var errorConfig = { - getDocsUrl: ({ docsBaseUrl, docsPath: docsPath4 = "", docsSlug }) => docsPath4 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath4}${docsSlug ? `#${docsSlug}` : ""}` : void 0, - version: `viem@${version2}` -}; -var BaseError2 = class _BaseError extends Error { - constructor(shortMessage, args = {}) { - const details = (() => { - if (args.cause instanceof _BaseError) - return args.cause.details; - if (args.cause?.message) - return args.cause.message; - return args.details; - })(); - const docsPath4 = (() => { - if (args.cause instanceof _BaseError) - return args.cause.docsPath || args.docsPath; - return args.docsPath; - })(); - const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath4 }); - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsUrl ? [`Docs: ${docsUrl}`] : [], - ...details ? [`Details: ${details}`] : [], - ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] - ].join("\n"); - super(message, args.cause ? { cause: args.cause } : void 0); - 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, "version", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - this.details = details; - this.docsPath = docsPath4; - this.metaMessages = args.metaMessages; - this.name = args.name ?? this.name; - this.shortMessage = shortMessage; - this.version = version2; - } - walk(fn) { - return walk(this, fn); - } -}; -function walk(err, fn) { - if (fn?.(err)) - return err; - if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) - return walk(err.cause, fn); - return fn ? null : err; -} - -// ../../node_modules/viem/_esm/errors/chain.js -var ChainDoesNotSupportContract = class extends BaseError2 { - constructor({ blockNumber, chain, contract }) { - super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { - metaMessages: [ - "This could be due to any of the following:", - ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ - `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` - ] : [ - `- The chain does not have the contract "${contract.name}" configured.` - ] - ], - name: "ChainDoesNotSupportContract" - }); - } -}; -var ClientChainNotConfiguredError = class extends BaseError2 { - constructor() { - super("No chain was provided to the Client.", { - name: "ClientChainNotConfiguredError" - }); - } -}; -var InvalidChainIdError = class extends BaseError2 { - constructor({ chainId }) { - super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); - } -}; - -// ../../node_modules/viem/_esm/constants/solidity.js -var solidityError = { - inputs: [ - { - name: "message", - type: "string" - } - ], - name: "Error", - type: "error" -}; -var solidityPanic = { - inputs: [ - { - name: "reason", - type: "uint256" - } - ], - name: "Panic", - type: "error" -}; - -// ../../node_modules/viem/_esm/utils/abi/formatAbiItem.js -function formatAbiItem2(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}` : ""); -} - -// ../../node_modules/viem/_esm/utils/data/isHex.js -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"); -} - -// ../../node_modules/viem/_esm/utils/data/size.js -function size(value) { - if (isHex(value, { strict: false })) - return Math.ceil((value.length - 2) / 2); - return value.length; -} - -// ../../node_modules/viem/_esm/errors/abi.js -var AbiConstructorNotFoundError = class extends BaseError2 { - constructor({ docsPath: docsPath4 }) { - 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: docsPath4, - name: "AbiConstructorNotFoundError" - }); - } -}; -var AbiConstructorParamsNotFoundError = class extends BaseError2 { - constructor({ docsPath: docsPath4 }) { - 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: docsPath4, - name: "AbiConstructorParamsNotFoundError" - }); - } -}; -var AbiDecodingDataSizeTooSmallError = class extends BaseError2 { - constructor({ data, params, size: size2 }) { - super([`Data size of ${size2} bytes is too small for given parameters.`].join("\n"), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size2} bytes)` - ], - name: "AbiDecodingDataSizeTooSmallError" - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; - this.params = params; - this.size = size2; - } -}; -var AbiDecodingZeroDataError = class extends BaseError2 { - constructor() { - super('Cannot decode zero data ("0x") with ABI parameters.', { - name: "AbiDecodingZeroDataError" - }); - } -}; -var AbiEncodingArrayLengthMismatchError = class extends BaseError2 { - constructor({ expectedLength, givenLength, type }) { - super([ - `ABI encoding array length mismatch for type ${type}.`, - `Expected length: ${expectedLength}`, - `Given length: ${givenLength}` - ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); - } -}; -var AbiEncodingBytesSizeMismatchError = class extends BaseError2 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); - } -}; -var AbiEncodingLengthMismatchError = class extends BaseError2 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding params/values length mismatch.", - `Expected length (params): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); - } -}; -var AbiErrorSignatureNotFoundError = class extends BaseError2 { - constructor(signature, { docsPath: docsPath4 }) { - super([ - `Encoded error signature "${signature}" not found on ABI.`, - "Make sure you are using the correct ABI and that the error exists on it.", - `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` - ].join("\n"), { - docsPath: docsPath4, - name: "AbiErrorSignatureNotFoundError" - }); - Object.defineProperty(this, "signature", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.signature = signature; - } -}; -var AbiFunctionNotFoundError = class extends BaseError2 { - constructor(functionName, { docsPath: docsPath4 } = {}) { - 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: docsPath4, - name: "AbiFunctionNotFoundError" - }); - } -}; -var AbiFunctionOutputsNotFoundError = class extends BaseError2 { - constructor(functionName, { docsPath: docsPath4 }) { - super([ - `Function "${functionName}" does not contain any \`outputs\` on ABI.`, - "Cannot decode function result without knowing what the parameter types are.", - "Make sure you are using the correct ABI and that the function exists on it." - ].join("\n"), { - docsPath: docsPath4, - name: "AbiFunctionOutputsNotFoundError" - }); - } -}; -var AbiItemAmbiguityError = class extends BaseError2 { - constructor(x, y) { - super("Found ambiguous types in overloaded ABI items.", { - metaMessages: [ - `\`${x.type}\` in \`${formatAbiItem2(x.abiItem)}\`, and`, - `\`${y.type}\` in \`${formatAbiItem2(y.abiItem)}\``, - "", - "These types encode differently and cannot be distinguished at runtime.", - "Remove one of the ambiguous items in the ABI." - ], - name: "AbiItemAmbiguityError" - }); - } -}; -var BytesSizeMismatchError = class extends BaseError2 { - constructor({ expectedSize, givenSize }) { - super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { - name: "BytesSizeMismatchError" - }); - } -}; -var InvalidAbiEncodingTypeError = class extends BaseError2 { - constructor(type, { docsPath: docsPath4 }) { - super([ - `Type "${type}" is not a valid encoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath4, name: "InvalidAbiEncodingType" }); - } -}; -var InvalidAbiDecodingTypeError = class extends BaseError2 { - constructor(type, { docsPath: docsPath4 }) { - super([ - `Type "${type}" is not a valid decoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath4, name: "InvalidAbiDecodingType" }); - } -}; -var InvalidArrayError = class extends BaseError2 { - constructor(value) { - super([`Value "${value}" is not a valid array.`].join("\n"), { - name: "InvalidArrayError" - }); - } -}; -var InvalidDefinitionTypeError = class extends BaseError2 { - constructor(type) { - super([ - `"${type}" is not a valid definition type.`, - 'Valid types: "function", "event", "error"' - ].join("\n"), { name: "InvalidDefinitionTypeError" }); - } -}; - -// ../../node_modules/viem/_esm/errors/data.js -var SliceOffsetOutOfBoundsError = class extends BaseError2 { - constructor({ offset, position, size: size2 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); - } -}; -var SizeExceedsPaddingSizeError = class extends BaseError2 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); - } -}; -var InvalidBytesLengthError = class extends BaseError2 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); - } -}; - -// ../../node_modules/viem/_esm/utils/data/slice.js -function slice(value, start, end, { strict } = {}) { - if (isHex(value, { strict: false })) - return sliceHex(value, start, end, { - strict - }); - return sliceBytes(value, start, end, { - strict - }); -} -function assertStartOffset(value, start) { - if (typeof start === "number" && start > 0 && start > size(value) - 1) - throw new SliceOffsetOutOfBoundsError({ - offset: start, - position: "start", - size: size(value) - }); -} -function assertEndOffset(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError({ - offset: end, - position: "end", - size: size(value) - }); - } -} -function sliceBytes(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = value_.slice(start, end); - if (strict) - assertEndOffset(value, start, end); - return value; -} -function sliceHex(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; - if (strict) - assertEndOffset(value, start, end); - return value; -} - -// ../../node_modules/viem/_esm/utils/data/pad.js -function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) { - if (typeof hexOrBytes === "string") - return padHex(hexOrBytes, { dir, size: size2 }); - return padBytes(hexOrBytes, { dir, size: size2 }); -} -function padHex(hex_, { dir, size: size2 = 32 } = {}) { - if (size2 === null) - return hex_; - const hex = hex_.replace("0x", ""); - if (hex.length > size2 * 2) - throw new SizeExceedsPaddingSizeError({ - size: Math.ceil(hex.length / 2), - targetSize: size2, - type: "hex" - }); - return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; -} -function padBytes(bytes, { dir, size: size2 = 32 } = {}) { - if (size2 === null) - return bytes; - if (bytes.length > size2) - throw new SizeExceedsPaddingSizeError({ - size: bytes.length, - targetSize: size2, - type: "bytes" - }); - const paddedBytes = new Uint8Array(size2); - for (let i = 0; i < size2; i++) { - const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; - } - return paddedBytes; -} - -// ../../node_modules/viem/_esm/errors/encoding.js -var IntegerOutOfRangeError = class extends BaseError2 { - constructor({ max, min, signed, size: size2, value }) { - super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); - } -}; -var InvalidBytesBooleanError = class extends BaseError2 { - constructor(bytes) { - super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { - name: "InvalidBytesBooleanError" - }); - } -}; -var SizeOverflowError = class extends BaseError2 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); - } -}; - -// ../../node_modules/viem/_esm/utils/data/trim.js -function trim(hexOrBytes, { dir = "left" } = {}) { - let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; - let sliceLength = 0; - for (let i = 0; i < data.length - 1; i++) { - if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") - sliceLength++; - else - break; - } - data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); - if (typeof hexOrBytes === "string") { - if (data.length === 1 && dir === "right") - data = `${data}0`; - return `0x${data.length % 2 === 1 ? `0${data}` : data}`; - } - return data; -} - -// ../../node_modules/viem/_esm/utils/encoding/fromHex.js -function assertSize(hexOrBytes, { size: size2 }) { - if (size(hexOrBytes) > size2) - throw new SizeOverflowError({ - givenSize: size(hexOrBytes), - maxSize: size2 - }); -} -function hexToBigInt(hex, opts = {}) { - const { signed } = opts; - if (opts.size) - assertSize(hex, { size: opts.size }); - const value = BigInt(hex); - if (!signed) - return value; - const size2 = (hex.length - 2) / 2; - const max = (1n << BigInt(size2) * 8n - 1n) - 1n; - if (value <= max) - return value; - return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; -} -function hexToNumber(hex, opts = {}) { - return Number(hexToBigInt(hex, opts)); -} - -// ../../node_modules/viem/_esm/utils/encoding/toHex.js -var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); -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(value, opts); -} -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; -} -function bytesToHex(value, opts = {}) { - let string = ""; - for (let i = 0; i < value.length; i++) { - string += hexes[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; -} -function numberToHex(value_, opts = {}) { - const { signed, size: size2 } = opts; - const value = BigInt(value_); - let maxValue; - if (size2) { - if (signed) - maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n; - else - maxValue = 2n ** (BigInt(size2) * 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}` : void 0, - min: `${minValue}${suffix}`, - signed, - size: size2, - value: `${value_}${suffix}` - }); - } - const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; - if (size2) - return pad(hex, { size: size2 }); - return hex; -} -var encoder = /* @__PURE__ */ new TextEncoder(); -function stringToHex(value_, opts = {}) { - const value = encoder.encode(value_); - return bytesToHex(value, opts); -} - -// ../../node_modules/viem/_esm/utils/encoding/toBytes.js -var encoder2 = /* @__PURE__ */ new TextEncoder(); -function toBytes(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(value, opts); - return stringToBytes(value, opts); -} -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; -} -var 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 void 0; -} -function hexToBytes(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 === void 0 || nibbleRight === void 0) { - throw new BaseError2(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); - } - bytes[index] = nibbleLeft * 16 + nibbleRight; - } - return bytes; -} -function numberToBytes(value, opts) { - const hex = numberToHex(value, opts); - return hexToBytes(hex); -} -function stringToBytes(value, opts = {}) { - const bytes = encoder2.encode(value); - if (typeof opts.size === "number") { - assertSize(bytes, { size: opts.size }); - return pad(bytes, { dir: "right", size: opts.size }); - } - return bytes; -} - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/_assert.js -function anumber(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error("positive integer expected, got " + n); -} -function isBytes(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes(b, ...lengths) { - if (!isBytes(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); -} -function aexists(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 aoutput(out, instance) { - abytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least " + min); - } -} - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/_u64.js -var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -var _32n = /* @__PURE__ */ BigInt(32); -function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(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(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -var rotlSH = (h, l, s) => h << s | l >>> 32 - s; -var rotlSL = (h, l, s) => l << s | h >>> 32 - s; -var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; -var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/utils.js -var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -var rotr = (word, shift) => word << 32 - shift | word >>> shift; -var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -function byteSwap32(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); - } -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error("utf8ToBytes expected string, got " + typeof str); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - abytes(data); - return data; -} -var Hash = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -}; -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function wrapXOFConstructorWithOpts(hashCons) { - const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); - const tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (opts) => hashCons(opts); - return hashC; -} - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/sha3.js -var SHA3_PI = []; -var SHA3_ROTL = []; -var _SHA3_IOTA = []; -var _0n = /* @__PURE__ */ BigInt(0); -var _1n = /* @__PURE__ */ BigInt(1); -var _2n = /* @__PURE__ */ BigInt(2); -var _7n = /* @__PURE__ */ BigInt(7); -var _256n = /* @__PURE__ */ BigInt(256); -var _0x71n = /* @__PURE__ */ BigInt(113); -for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); - let t = _0n; - for (let j = 0; j < 7; j++) { - R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n; - if (R & _2n) - t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n; - } - _SHA3_IOTA.push(t); -} -var [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); -var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); -var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); -function keccakP(s, rounds = 24) { - const B = new Uint32Array(5 * 2); - for (let round = 24 - rounds; round < 24; round++) { - 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(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0; y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - 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]; - } - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - B.fill(0); -} -var Keccak = class _Keccak extends Hash { - // 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; - anumber(outputLen); - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error("Sha3 supports only keccak-f1600 function"); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - keccak() { - if (!isLE) - byteSwap32(this.state32); - keccakP(this.state32, this.rounds); - if (!isLE) - byteSwap32(this.state32); - this.posOut = 0; - this.pos = 0; - } - update(data) { - aexists(this); - const { blockLen, state } = this; - data = toBytes2(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; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); - } - writeInto(out) { - aexists(this, false); - abytes(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) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); - } - xof(bytes) { - anumber(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - aoutput(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; - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } -}; -var gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); -var sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); -var sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); -var sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); -var sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); -var keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); -var keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); -var keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); -var keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); -var genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); -var shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); -var shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); - -// ../../node_modules/viem/_esm/utils/hash/keccak256.js -function keccak256(value, to_) { - const to = to_ || "hex"; - const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); - if (to === "bytes") - return bytes; - return toHex(bytes); -} - -// ../../node_modules/viem/_esm/utils/hash/hashSignature.js -var hash = (value) => keccak256(toBytes(value)); -function hashSignature(sig) { - return hash(sig); -} - -// ../../node_modules/viem/_esm/utils/hash/normalizeSignature.js -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 (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; - } - } - continue; - } - if (char === " ") { - if (signature[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; - } - continue; - } - result += char; - current += char; - } - if (!valid) - throw new BaseError2("Unable to normalize signature."); - return result; -} - -// ../../node_modules/viem/_esm/utils/hash/toSignature.js -var toSignature = (def) => { - const def_ = (() => { - if (typeof def === "string") - return def; - return formatAbiItem(def); - })(); - return normalizeSignature(def_); -}; - -// ../../node_modules/viem/_esm/utils/hash/toSignatureHash.js -function toSignatureHash(fn) { - return hashSignature(toSignature(fn)); -} - -// ../../node_modules/viem/_esm/utils/hash/toFunctionSelector.js -var toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); - -// ../../node_modules/viem/_esm/errors/address.js -var InvalidAddressError = class extends BaseError2 { - 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." - ], - name: "InvalidAddressError" - }); - } -}; - -// ../../node_modules/viem/_esm/utils/lru.js -var LruMap = class extends Map { - constructor(size2) { - super(); - Object.defineProperty(this, "maxSize", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxSize = size2; - } - get(key) { - const value = super.get(key); - if (super.has(key) && value !== void 0) { - this.delete(key); - super.set(key, value); - } - return value; - } - set(key, value) { - super.set(key, value); - if (this.maxSize && this.size > this.maxSize) { - const firstKey = this.keys().next().value; - if (firstKey) - this.delete(firstKey); - } - return this; - } -}; - -// ../../node_modules/viem/_esm/utils/address/isAddress.js -var addressRegex = /^0x[a-fA-F0-9]{40}$/; -var isAddressCache = /* @__PURE__ */ new LruMap(8192); -function isAddress(address, options) { - const { strict = true } = options ?? {}; - const cacheKey = `${address}.${strict}`; - if (isAddressCache.has(cacheKey)) - return isAddressCache.get(cacheKey); - const result = (() => { - if (!addressRegex.test(address)) - return false; - if (address.toLowerCase() === address) - return true; - if (strict) - return checksumAddress(address) === address; - return true; - })(); - isAddressCache.set(cacheKey, result); - return result; -} - -// ../../node_modules/viem/_esm/utils/address/getAddress.js -var checksumAddressCache = /* @__PURE__ */ new LruMap(8192); -function checksumAddress(address_, chainId) { - if (checksumAddressCache.has(`${address_}.${chainId}`)) - return checksumAddressCache.get(`${address_}.${chainId}`); - const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); - const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); - const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); - for (let i = 0; i < 40; i += 2) { - if (hash2[i >> 1] >> 4 >= 8 && address[i]) { - address[i] = address[i].toUpperCase(); - } - if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { - address[i + 1] = address[i + 1].toUpperCase(); - } - } - const result = `0x${address.join("")}`; - checksumAddressCache.set(`${address_}.${chainId}`, result); - return result; -} - -// ../../node_modules/viem/_esm/errors/cursor.js -var NegativeOffsetError = class extends BaseError2 { - constructor({ offset }) { - super(`Offset \`${offset}\` cannot be negative.`, { - name: "NegativeOffsetError" - }); - } -}; -var PositionOutOfBoundsError = class extends BaseError2 { - constructor({ length, position }) { - super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); - } -}; -var RecursiveReadLimitExceededError = class extends BaseError2 { - constructor({ count, limit }) { - super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); - } -}; - -// ../../node_modules/viem/_esm/utils/cursor.js -var staticCursor = { - bytes: new Uint8Array(), - dataView: new DataView(new ArrayBuffer(0)), - position: 0, - positionReadCount: /* @__PURE__ */ new Map(), - recursiveReadCount: 0, - recursiveReadLimit: Number.POSITIVE_INFINITY, - assertReadLimit() { - if (this.recursiveReadCount >= this.recursiveReadLimit) - throw new RecursiveReadLimitExceededError({ - count: this.recursiveReadCount + 1, - limit: this.recursiveReadLimit - }); - }, - assertPosition(position) { - if (position < 0 || position > this.bytes.length - 1) - throw new PositionOutOfBoundsError({ - length: this.bytes.length, - position - }); - }, - decrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position - offset; - this.assertPosition(position); - this.position = position; - }, - getReadCount(position) { - return this.positionReadCount.get(position || this.position) || 0; - }, - incrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position + offset; - this.assertPosition(position); - this.position = position; - }, - inspectByte(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectBytes(length, position_) { - const position = position_ ?? this.position; - this.assertPosition(position + length - 1); - return this.bytes.subarray(position, position + length); - }, - inspectUint8(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectUint16(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 1); - return this.dataView.getUint16(position); - }, - inspectUint24(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 2); - return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); - }, - inspectUint32(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 3); - return this.dataView.getUint32(position); - }, - pushByte(byte) { - this.assertPosition(this.position); - this.bytes[this.position] = byte; - this.position++; - }, - pushBytes(bytes) { - this.assertPosition(this.position + bytes.length - 1); - this.bytes.set(bytes, this.position); - this.position += bytes.length; - }, - pushUint8(value) { - this.assertPosition(this.position); - this.bytes[this.position] = value; - this.position++; - }, - pushUint16(value) { - this.assertPosition(this.position + 1); - this.dataView.setUint16(this.position, value); - this.position += 2; - }, - pushUint24(value) { - this.assertPosition(this.position + 2); - this.dataView.setUint16(this.position, value >> 8); - this.dataView.setUint8(this.position + 2, value & ~4294967040); - this.position += 3; - }, - pushUint32(value) { - this.assertPosition(this.position + 3); - this.dataView.setUint32(this.position, value); - this.position += 4; - }, - readByte() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectByte(); - this.position++; - return value; - }, - readBytes(length, size2) { - this.assertReadLimit(); - this._touch(); - const value = this.inspectBytes(length); - this.position += size2 ?? length; - return value; - }, - readUint8() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint8(); - this.position += 1; - return value; - }, - readUint16() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint16(); - this.position += 2; - return value; - }, - readUint24() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint24(); - this.position += 3; - return value; - }, - readUint32() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint32(); - this.position += 4; - return value; - }, - get remaining() { - return this.bytes.length - this.position; - }, - setPosition(position) { - const oldPosition = this.position; - this.assertPosition(position); - this.position = position; - return () => this.position = oldPosition; - }, - _touch() { - if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) - return; - const count = this.getReadCount(); - this.positionReadCount.set(this.position, count + 1); - if (count > 0) - this.recursiveReadCount++; - } -}; -function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { - const cursor = Object.create(staticCursor); - cursor.bytes = bytes; - cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - cursor.positionReadCount = /* @__PURE__ */ new Map(); - cursor.recursiveReadLimit = recursiveReadLimit; - return cursor; -} - -// ../../node_modules/viem/_esm/utils/encoding/fromBytes.js -function bytesToBigInt(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes, opts); - return hexToBigInt(hex, opts); -} -function bytesToBool(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim(bytes); - } - if (bytes.length > 1 || bytes[0] > 1) - throw new InvalidBytesBooleanError(bytes); - return Boolean(bytes[0]); -} -function bytesToNumber(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes, opts); - return hexToNumber(hex, opts); -} -function bytesToString(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim(bytes, { dir: "right" }); - } - return new TextDecoder().decode(bytes); -} - -// ../../node_modules/viem/_esm/utils/data/concat.js -function concat(values) { - if (typeof values[0] === "string") - return concatHex(values); - return concatBytes(values); -} -function concatBytes(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; - } - return result; -} -function concatHex(values) { - return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; -} - -// ../../node_modules/viem/_esm/utils/regex.js -var bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; -var integerRegex2 = /^(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/encodeAbiParameters.js -function encodeAbiParameters(params, values) { - if (params.length !== values.length) - throw new AbiEncodingLengthMismatchError({ - expectedLength: params.length, - givenLength: values.length - }); - const preparedParams = prepareParams({ - params, - values - }); - const data = encodeParams(preparedParams); - if (data.length === 0) - return "0x"; - return data; -} -function prepareParams({ params, values }) { - const preparedParams = []; - for (let i = 0; i < params.length; i++) { - preparedParams.push(prepareParam({ param: params[i], value: values[i] })); - } - return preparedParams; -} -function prepareParam({ param, value }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return encodeArray(value, { length, param: { ...param, type } }); - } - if (param.type === "tuple") { - return encodeTuple(value, { - param - }); - } - if (param.type === "address") { - return encodeAddress(value); - } - if (param.type === "bool") { - return encodeBool(value); - } - if (param.type.startsWith("uint") || param.type.startsWith("int")) { - const signed = param.type.startsWith("int"); - const [, , size2 = "256"] = integerRegex2.exec(param.type) ?? []; - return encodeNumber(value, { - signed, - size: Number(size2) - }); - } - if (param.type.startsWith("bytes")) { - return encodeBytes(value, { param }); - } - if (param.type === "string") { - return encodeString(value); - } - throw new InvalidAbiEncodingTypeError(param.type, { - docsPath: "/docs/contract/encodeAbiParameters" - }); -} -function encodeParams(preparedParams) { - let staticSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) - staticSize += 32; - else - staticSize += size(encoded); - } - const staticParams = []; - const dynamicParams = []; - let dynamicSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) { - staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); - dynamicParams.push(encoded); - dynamicSize += size(encoded); - } else { - staticParams.push(encoded); - } - } - return concat([...staticParams, ...dynamicParams]); -} -function encodeAddress(value) { - if (!isAddress(value)) - throw new InvalidAddressError({ address: value }); - return { dynamic: false, encoded: padHex(value.toLowerCase()) }; -} -function encodeArray(value, { length, param }) { - const dynamic = length === null; - if (!Array.isArray(value)) - throw new InvalidArrayError(value); - if (!dynamic && value.length !== length) - throw new AbiEncodingArrayLengthMismatchError({ - expectedLength: length, - givenLength: value.length, - type: `${param.type}[${length}]` - }); - let dynamicChild = false; - const preparedParams = []; - for (let i = 0; i < value.length; i++) { - const preparedParam = prepareParam({ param, value: value[i] }); - if (preparedParam.dynamic) - dynamicChild = true; - preparedParams.push(preparedParam); - } - if (dynamic || dynamicChild) { - const data = encodeParams(preparedParams); - if (dynamic) { - const length2 = numberToHex(preparedParams.length, { size: 32 }); - return { - dynamic: true, - encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 - }; - } - if (dynamicChild) - return { dynamic: true, encoded: data }; - } - return { - dynamic: false, - encoded: concat(preparedParams.map(({ encoded }) => encoded)) - }; -} -function encodeBytes(value, { param }) { - const [, paramSize] = param.type.split("bytes"); - const bytesSize = size(value); - if (!paramSize) { - let value_ = value; - if (bytesSize % 32 !== 0) - value_ = padHex(value_, { - dir: "right", - size: Math.ceil((value.length - 2) / 2 / 32) * 32 - }); - return { - dynamic: true, - encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) - }; - } - if (bytesSize !== Number.parseInt(paramSize)) - throw new AbiEncodingBytesSizeMismatchError({ - expectedSize: Number.parseInt(paramSize), - value - }); - return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; -} -function encodeBool(value) { - if (typeof value !== "boolean") - throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); - return { dynamic: false, encoded: padHex(boolToHex(value)) }; -} -function encodeNumber(value, { signed, size: size2 = 256 }) { - if (typeof size2 === "number") { - const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n; - const min = signed ? -max - 1n : 0n; - if (value > max || value < min) - throw new IntegerOutOfRangeError({ - max: max.toString(), - min: min.toString(), - signed, - size: size2 / 8, - value: value.toString() - }); - } - return { - dynamic: false, - encoded: numberToHex(value, { - size: 32, - signed - }) - }; -} -function encodeString(value) { - const hexValue = stringToHex(value); - const partsLength = Math.ceil(size(hexValue) / 32); - const parts = []; - for (let i = 0; i < partsLength; i++) { - parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { - dir: "right" - })); - } - return { - dynamic: true, - encoded: concat([ - padHex(numberToHex(size(hexValue), { size: 32 })), - ...parts - ]) - }; -} -function encodeTuple(value, { param }) { - let dynamic = false; - const preparedParams = []; - for (let i = 0; i < param.components.length; i++) { - const param_ = param.components[i]; - const index = Array.isArray(value) ? i : param_.name; - const preparedParam = prepareParam({ - param: param_, - value: value[index] - }); - preparedParams.push(preparedParam); - if (preparedParam.dynamic) - dynamic = true; - } - return { - dynamic, - encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) - }; -} -function getArrayComponents(type) { - const matches = type.match(/^(.*)\[(\d+)?\]$/); - return matches ? ( - // Return `null` if the array is dynamic. - [matches[2] ? Number(matches[2]) : null, matches[1]] - ) : void 0; -} - -// ../../node_modules/viem/_esm/utils/abi/decodeAbiParameters.js -function decodeAbiParameters(params, data) { - const bytes = typeof data === "string" ? hexToBytes(data) : data; - const cursor = createCursor(bytes); - if (size(bytes) === 0 && params.length > 0) - throw new AbiDecodingZeroDataError(); - if (size(data) && size(data) < 32) - throw new AbiDecodingDataSizeTooSmallError({ - data: typeof data === "string" ? data : bytesToHex(data), - params, - size: size(data) - }); - let consumed = 0; - const values = []; - for (let i = 0; i < params.length; ++i) { - const param = params[i]; - cursor.setPosition(consumed); - const [data2, consumed_] = decodeParameter(cursor, param, { - staticPosition: 0 - }); - consumed += consumed_; - values.push(data2); - } - return values; -} -function decodeParameter(cursor, param, { staticPosition }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return decodeArray(cursor, { ...param, type }, { length, staticPosition }); - } - if (param.type === "tuple") - return decodeTuple(cursor, param, { staticPosition }); - if (param.type === "address") - return decodeAddress(cursor); - if (param.type === "bool") - return decodeBool(cursor); - if (param.type.startsWith("bytes")) - return decodeBytes(cursor, param, { staticPosition }); - if (param.type.startsWith("uint") || param.type.startsWith("int")) - return decodeNumber(cursor, param); - if (param.type === "string") - return decodeString(cursor, { staticPosition }); - throw new InvalidAbiDecodingTypeError(param.type, { - docsPath: "/docs/contract/decodeAbiParameters" - }); -} -var sizeOfLength = 32; -var sizeOfOffset = 32; -function decodeAddress(cursor) { - const value = cursor.readBytes(32); - return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; -} -function decodeArray(cursor, param, { length, staticPosition }) { - if (!length) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const startOfData = start + sizeOfLength; - cursor.setPosition(start); - const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); - const dynamicChild = hasDynamicChild(param); - let consumed2 = 0; - const value2 = []; - for (let i = 0; i < length2; ++i) { - cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: startOfData - }); - consumed2 += consumed_; - value2.push(data); - } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const value2 = []; - for (let i = 0; i < length; ++i) { - cursor.setPosition(start + i * 32); - const [data] = decodeParameter(cursor, param, { - staticPosition: start - }); - value2.push(data); - } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - let consumed = 0; - const value = []; - for (let i = 0; i < length; ++i) { - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: staticPosition + consumed - }); - consumed += consumed_; - value.push(data); - } - return [value, consumed]; -} -function decodeBool(cursor) { - return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; -} -function decodeBytes(cursor, param, { staticPosition }) { - const [_, size2] = param.type.split("bytes"); - if (!size2) { - const offset = bytesToNumber(cursor.readBytes(32)); - cursor.setPosition(staticPosition + offset); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["0x", 32]; - } - const data = cursor.readBytes(length); - cursor.setPosition(staticPosition + 32); - return [bytesToHex(data), 32]; - } - const value = bytesToHex(cursor.readBytes(Number.parseInt(size2), 32)); - return [value, 32]; -} -function decodeNumber(cursor, param) { - const signed = param.type.startsWith("int"); - const size2 = Number.parseInt(param.type.split("int")[1] || "256"); - const value = cursor.readBytes(32); - return [ - size2 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), - 32 - ]; -} -function decodeTuple(cursor, param, { staticPosition }) { - const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); - const value = hasUnnamedChild ? [] : {}; - let consumed = 0; - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - cursor.setPosition(start + consumed); - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition: start - }); - consumed += consumed_; - value[hasUnnamedChild ? i : component?.name] = data; - } - cursor.setPosition(staticPosition + 32); - return [value, 32]; - } - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition - }); - value[hasUnnamedChild ? i : component?.name] = data; - consumed += consumed_; - } - return [value, consumed]; -} -function decodeString(cursor, { staticPosition }) { - const offset = bytesToNumber(cursor.readBytes(32)); - const start = staticPosition + offset; - cursor.setPosition(start); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["", 32]; - } - const data = cursor.readBytes(length, 32); - const value = bytesToString(trim(data)); - cursor.setPosition(staticPosition + 32); - return [value, 32]; -} -function hasDynamicChild(param) { - const { type } = param; - if (type === "string") - return true; - if (type === "bytes") - return true; - if (type.endsWith("[]")) - return true; - if (type === "tuple") - return param.components?.some(hasDynamicChild); - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) - return true; - return false; -} - -// ../../node_modules/viem/_esm/utils/abi/decodeErrorResult.js -function decodeErrorResult(parameters) { - const { abi, data } = parameters; - const signature = slice(data, 0, 4); - if (signature === "0x") - throw new AbiDecodingZeroDataError(); - const abi_ = [...abi || [], solidityError, solidityPanic]; - const abiItem = abi_.find((x) => x.type === "error" && signature === toFunctionSelector(formatAbiItem2(x))); - if (!abiItem) - throw new AbiErrorSignatureNotFoundError(signature, { - docsPath: "/docs/contract/decodeErrorResult" - }); - return { - abiItem, - args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, - errorName: abiItem.name - }; -} - -// ../../node_modules/viem/_esm/utils/stringify.js -var stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { - const value2 = typeof value_ === "bigint" ? value_.toString() : value_; - return typeof replacer === "function" ? replacer(key, value2) : value2; -}, space); - -// ../../node_modules/viem/_esm/utils/hash/toEventSelector.js -var toEventSelector = toSignatureHash; - -// ../../node_modules/viem/_esm/utils/abi/getAbiItem.js -function getAbiItem(parameters) { - const { abi, args = [], name } = parameters; - const isSelector = isHex(name, { strict: false }); - const abiItems = abi.filter((abiItem) => { - if (isSelector) { - if (abiItem.type === "function") - return toFunctionSelector(abiItem) === name; - if (abiItem.type === "event") - return toEventSelector(abiItem) === name; - return false; - } - return "name" in abiItem && abiItem.name === name; - }); - if (abiItems.length === 0) - return void 0; - if (abiItems.length === 1) - return abiItems[0]; - let matchedAbiItem = void 0; - for (const abiItem of abiItems) { - if (!("inputs" in abiItem)) - continue; - if (!args || args.length === 0) { - if (!abiItem.inputs || abiItem.inputs.length === 0) - return abiItem; - continue; - } - if (!abiItem.inputs) - continue; - if (abiItem.inputs.length === 0) - continue; - if (abiItem.inputs.length !== args.length) - continue; - const matched = args.every((arg, index) => { - const abiParameter = "inputs" in abiItem && abiItem.inputs[index]; - if (!abiParameter) - return false; - return isArgOfType(arg, abiParameter); - }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AbiItemAmbiguityError({ - abiItem, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); - } - matchedAbiItem = abiItem; - } - } - if (matchedAbiItem) - return matchedAbiItem; - return abiItems[0]; -} -function isArgOfType(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return isAddress(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index) => { - return isArgOfType(Object.values(arg)[index], component); - }); - if (/^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(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x) => isArgOfType(x, { - ...abiParameter, - // Pop off `[]` or `[M]` from end of type - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); - } - return false; - } - } -} -function getAmbiguousTypes(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types.includes("address") && types.includes("bytes20")) - return true; - if (types.includes("address") && types.includes("string")) - return isAddress(args[parameterIndex], { strict: false }); - if (types.includes("address") && types.includes("bytes")) - return isAddress(args[parameterIndex], { strict: false }); - return false; - })(); - if (ambiguous) - return types; - } - return; -} - -// ../../node_modules/viem/_esm/constants/unit.js -var etherUnits = { - gwei: 9, - wei: 18 -}; -var gweiUnits = { - ether: -9, - wei: 9 -}; - -// ../../node_modules/viem/_esm/utils/unit/formatUnits.js -function formatUnits(value, decimals) { - let display = value.toString(); - const negative = display.startsWith("-"); - if (negative) - display = display.slice(1); - display = display.padStart(decimals, "0"); - let [integer, fraction] = [ - display.slice(0, display.length - decimals), - display.slice(display.length - decimals) - ]; - fraction = fraction.replace(/(0+)$/, ""); - return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; -} - -// ../../node_modules/viem/_esm/utils/unit/formatEther.js -function formatEther(wei, unit = "wei") { - return formatUnits(wei, etherUnits[unit]); -} - -// ../../node_modules/viem/_esm/utils/unit/formatGwei.js -function formatGwei(wei, unit = "wei") { - return formatUnits(wei, gweiUnits[unit]); -} - -// ../../node_modules/viem/_esm/errors/stateOverride.js -var AccountStateConflictError = class extends BaseError2 { - constructor({ address }) { - super(`State for account "${address}" is set multiple times.`, { - name: "AccountStateConflictError" - }); - } -}; -var StateAssignmentConflictError = class extends BaseError2 { - constructor() { - super("state and stateDiff are set on the same account.", { - name: "StateAssignmentConflictError" - }); - } -}; -function prettyStateMapping(stateMapping) { - return stateMapping.reduce((pretty, { slot, value }) => { - return `${pretty} ${slot}: ${value} -`; - }, ""); -} -function prettyStateOverride(stateOverride) { - return stateOverride.reduce((pretty, { address, ...state }) => { - let val = `${pretty} ${address}: -`; - if (state.nonce) - val += ` nonce: ${state.nonce} -`; - if (state.balance) - val += ` balance: ${state.balance} -`; - if (state.code) - val += ` code: ${state.code} -`; - if (state.state) { - val += " state:\n"; - val += prettyStateMapping(state.state); - } - if (state.stateDiff) { - val += " stateDiff:\n"; - val += prettyStateMapping(state.stateDiff); - } - return val; - }, " State Override:\n").slice(0, -1); -} - -// ../../node_modules/viem/_esm/errors/transaction.js -function prettyPrint(args) { - const entries = Object.entries(args).map(([key, value]) => { - if (value === void 0 || value === false) - return null; - return [key, value]; - }).filter(Boolean); - const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); - return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); -} -var FeeConflictError = class extends BaseError2 { - constructor() { - super([ - "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", - "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." - ].join("\n"), { name: "FeeConflictError" }); - } -}; -var InvalidLegacyVError = class extends BaseError2 { - constructor({ v }) { - super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, { - name: "InvalidLegacyVError" - }); - } -}; -var InvalidSerializableTransactionError = class extends BaseError2 { - constructor({ transaction }) { - super("Cannot infer a transaction type from provided transaction.", { - metaMessages: [ - "Provided Transaction:", - "{", - prettyPrint(transaction), - "}", - "", - "To infer the type, either provide:", - "- a `type` to the Transaction, or", - "- an EIP-1559 Transaction with `maxFeePerGas`, or", - "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", - "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", - "- an EIP-7702 Transaction with `authorizationList`, or", - "- a Legacy Transaction with `gasPrice`" - ], - name: "InvalidSerializableTransactionError" - }); - } -}; -var InvalidStorageKeySizeError = class extends BaseError2 { - constructor({ storageKey }) { - super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" }); - } -}; - -// ../../node_modules/viem/_esm/errors/utils.js -var getUrl = (url) => url; - -// ../../node_modules/viem/_esm/errors/contract.js -var CallExecutionError = class extends BaseError2 { - constructor(cause, { account: account_, docsPath: docsPath4, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride }) { - const account = account_ ? parseAccount(account_) : void 0; - let 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 - }); - if (stateOverride) { - prettyArgs += ` -${prettyStateOverride(stateOverride)}`; - } - super(cause.shortMessage, { - cause, - docsPath: docsPath4, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Raw Call Arguments:", - prettyArgs - ].filter(Boolean), - name: "CallExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; - } -}; -var CounterfactualDeploymentFailedError = class extends BaseError2 { - constructor({ factory }) { - super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, { - metaMessages: [ - "Please ensure:", - "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", - "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." - ], - name: "CounterfactualDeploymentFailedError" - }); - } -}; -var RawContractError = class extends BaseError2 { - constructor({ data, message }) { - super(message || "", { name: "RawContractError" }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; - } -}; - -// ../../node_modules/viem/_esm/utils/abi/decodeFunctionResult.js -var docsPath = "/docs/contract/decodeFunctionResult"; -function decodeFunctionResult(parameters) { - const { abi, args, functionName, data } = parameters; - let abiItem = abi[0]; - if (functionName) { - const item = getAbiItem({ abi, args, name: functionName }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath }); - abiItem = item; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath }); - if (!abiItem.outputs) - throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath }); - const values = decodeAbiParameters(abiItem.outputs, data); - if (values && values.length > 1) - return values; - if (values && values.length === 1) - return values[0]; - return void 0; -} - -// ../../node_modules/viem/_esm/utils/abi/encodeDeployData.js -var docsPath2 = "/docs/contract/encodeDeployData"; -function encodeDeployData(parameters) { - const { abi, args, bytecode } = parameters; - if (!args || args.length === 0) - return bytecode; - const description = abi.find((x) => "type" in x && x.type === "constructor"); - if (!description) - throw new AbiConstructorNotFoundError({ docsPath: docsPath2 }); - if (!("inputs" in description)) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 }); - if (!description.inputs || description.inputs.length === 0) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 }); - const data = encodeAbiParameters(description.inputs, args); - return concatHex([bytecode, data]); -} - -// ../../node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js -var docsPath3 = "/docs/contract/encodeFunctionData"; -function prepareEncodeFunctionData(parameters) { - const { abi, args, functionName } = parameters; - let abiItem = abi[0]; - if (functionName) { - const item = getAbiItem({ - abi, - args, - name: functionName - }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath3 }); - abiItem = item; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath3 }); - return { - abi: [abiItem], - functionName: toFunctionSelector(formatAbiItem2(abiItem)) - }; -} - -// ../../node_modules/viem/_esm/utils/abi/encodeFunctionData.js -function encodeFunctionData(parameters) { - const { args } = parameters; - const { abi, functionName } = (() => { - if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) - return parameters; - return prepareEncodeFunctionData(parameters); - })(); - const abiItem = abi[0]; - const signature = functionName; - const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; - return concatHex([signature, data ?? "0x"]); -} - -// ../../node_modules/viem/_esm/utils/chain/getChainContractAddress.js -function getChainContractAddress({ blockNumber, chain, contract: name }) { - const contract = chain?.contracts?.[name]; - if (!contract) - throw new ChainDoesNotSupportContract({ - chain, - contract: { name } - }); - if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) - throw new ChainDoesNotSupportContract({ - blockNumber, - chain, - contract: { - name, - blockCreated: contract.blockCreated - } - }); - return contract.address; -} - -// ../../node_modules/viem/_esm/errors/node.js -var ExecutionRevertedError = class extends BaseError2 { - constructor({ cause, message } = {}) { - const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); - super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { - cause, - name: "ExecutionRevertedError" - }); - } -}; -Object.defineProperty(ExecutionRevertedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 -}); -Object.defineProperty(ExecutionRevertedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /execution reverted/ -}); -var FeeCapTooHighError = class extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { - cause, - name: "FeeCapTooHighError" - }); - } -}; -Object.defineProperty(FeeCapTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ -}); -var FeeCapTooLowError = class extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { - cause, - name: "FeeCapTooLowError" - }); - } -}; -Object.defineProperty(FeeCapTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ -}); -var NonceTooHighError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); - } -}; -Object.defineProperty(NonceTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too high/ -}); -var NonceTooLowError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super([ - `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, - "Try increasing the nonce or find the latest nonce with `getTransactionCount`." - ].join("\n"), { cause, name: "NonceTooLowError" }); - } -}; -Object.defineProperty(NonceTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too low|transaction already imported|already known/ -}); -var NonceMaxValueError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); - } -}; -Object.defineProperty(NonceMaxValueError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce has max value/ -}); -var InsufficientFundsError = class extends BaseError2 { - constructor({ cause } = {}) { - super([ - "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." - ].join("\n"), { - cause, - metaMessages: [ - "This error could arise when the account does not have enough funds to:", - " - pay for the total gas fee,", - " - pay for the value to send.", - " ", - "The cost of the transaction is calculated as `gas * gas fee + value`, where:", - " - `gas` is the amount of gas needed for transaction to execute,", - " - `gas fee` is the gas fee,", - " - `value` is the amount of ether to send to the recipient." - ], - name: "InsufficientFundsError" - }); - } -}; -Object.defineProperty(InsufficientFundsError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /insufficient funds|exceeds transaction sender account balance/ -}); -var IntrinsicGasTooHighError = class extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { - cause, - name: "IntrinsicGasTooHighError" - }); - } -}; -Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too high|gas limit reached/ -}); -var IntrinsicGasTooLowError = class extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { - cause, - name: "IntrinsicGasTooLowError" - }); - } -}; -Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too low/ -}); -var TransactionTypeNotSupportedError = class extends BaseError2 { - constructor({ cause }) { - super("The transaction type is not supported for this chain.", { - cause, - name: "TransactionTypeNotSupportedError" - }); - } -}; -Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /transaction type not valid/ -}); -var TipAboveFeeCapError = class extends BaseError2 { - constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { - super([ - `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` - ].join("\n"), { - cause, - name: "TipAboveFeeCapError" - }); - } -}; -Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ -}); -var UnknownNodeError = class extends BaseError2 { - constructor({ cause }) { - super(`An error occurred while executing: ${cause?.shortMessage}`, { - cause, - name: "UnknownNodeError" - }); - } -}; - -// ../../node_modules/viem/_esm/errors/request.js -var HttpRequestError = class extends BaseError2 { - constructor({ body, cause, details, headers, status, url }) { - super("HTTP request failed.", { - cause, - details, - metaMessages: [ - status && `Status: ${status}`, - `URL: ${getUrl(url)}`, - body && `Request body: ${stringify(body)}` - ].filter(Boolean), - name: "HttpRequestError" - }); - Object.defineProperty(this, "body", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "url", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.body = body; - this.headers = headers; - this.status = status; - this.url = url; - } -}; - -// ../../node_modules/viem/_esm/utils/errors/getNodeError.js -function getNodeError(err, args) { - const message = (err.details || "").toLowerCase(); - const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; - if (executionRevertedError instanceof BaseError2) - return new ExecutionRevertedError({ - cause: err, - message: executionRevertedError.details - }); - if (ExecutionRevertedError.nodeMessage.test(message)) - return new ExecutionRevertedError({ - cause: err, - message: err.details - }); - if (FeeCapTooHighError.nodeMessage.test(message)) - return new FeeCapTooHighError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas - }); - if (FeeCapTooLowError.nodeMessage.test(message)) - return new FeeCapTooLowError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas - }); - if (NonceTooHighError.nodeMessage.test(message)) - return new NonceTooHighError({ cause: err, nonce: args?.nonce }); - if (NonceTooLowError.nodeMessage.test(message)) - return new NonceTooLowError({ cause: err, nonce: args?.nonce }); - if (NonceMaxValueError.nodeMessage.test(message)) - return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); - if (InsufficientFundsError.nodeMessage.test(message)) - return new InsufficientFundsError({ cause: err }); - if (IntrinsicGasTooHighError.nodeMessage.test(message)) - return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); - if (IntrinsicGasTooLowError.nodeMessage.test(message)) - return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); - if (TransactionTypeNotSupportedError.nodeMessage.test(message)) - return new TransactionTypeNotSupportedError({ cause: err }); - if (TipAboveFeeCapError.nodeMessage.test(message)) - return new TipAboveFeeCapError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas, - maxPriorityFeePerGas: args?.maxPriorityFeePerGas - }); - return new UnknownNodeError({ - cause: err - }); -} - -// ../../node_modules/viem/_esm/utils/errors/getCallError.js -function getCallError(err, { docsPath: docsPath4, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new CallExecutionError(cause, { - docsPath: docsPath4, - ...args - }); -} - -// ../../node_modules/viem/_esm/utils/formatters/extract.js -function extract(value_, { format }) { - if (!format) - return {}; - const value = {}; - function extract_(formatted2) { - const keys = Object.keys(formatted2); - for (const key of keys) { - if (key in value_) - value[key] = value_[key]; - if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) - extract_(formatted2[key]); - } - } - const formatted = format(value_ || {}); - extract_(formatted); - return value; -} - -// ../../node_modules/viem/_esm/utils/formatters/transactionRequest.js -var rpcTransactionType = { - legacy: "0x0", - eip2930: "0x1", - eip1559: "0x2", - eip4844: "0x3", - eip7702: "0x4" -}; -function formatTransactionRequest(request) { - const rpcRequest = {}; - if (typeof request.authorizationList !== "undefined") - rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); - if (typeof request.accessList !== "undefined") - rpcRequest.accessList = request.accessList; - if (typeof request.blobVersionedHashes !== "undefined") - rpcRequest.blobVersionedHashes = request.blobVersionedHashes; - if (typeof request.blobs !== "undefined") { - if (typeof request.blobs[0] !== "string") - rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x)); - else - rpcRequest.blobs = request.blobs; - } - if (typeof request.data !== "undefined") - rpcRequest.data = request.data; - if (typeof request.from !== "undefined") - rpcRequest.from = request.from; - if (typeof request.gas !== "undefined") - rpcRequest.gas = numberToHex(request.gas); - if (typeof request.gasPrice !== "undefined") - rpcRequest.gasPrice = numberToHex(request.gasPrice); - if (typeof request.maxFeePerBlobGas !== "undefined") - rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); - if (typeof request.maxFeePerGas !== "undefined") - rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); - if (typeof request.maxPriorityFeePerGas !== "undefined") - rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); - if (typeof request.nonce !== "undefined") - rpcRequest.nonce = numberToHex(request.nonce); - if (typeof request.to !== "undefined") - rpcRequest.to = request.to; - if (typeof request.type !== "undefined") - rpcRequest.type = rpcTransactionType[request.type]; - if (typeof request.value !== "undefined") - rpcRequest.value = numberToHex(request.value); - return rpcRequest; -} -function formatAuthorizationList(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.contractAddress, - r: authorization.r, - s: authorization.s, - chainId: numberToHex(authorization.chainId), - nonce: numberToHex(authorization.nonce), - ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, - ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} - })); -} - -// ../../node_modules/viem/_esm/utils/promise/withResolvers.js -function withResolvers() { - let resolve = () => void 0; - let reject = () => void 0; - const promise = new Promise((resolve_, reject_) => { - resolve = resolve_; - reject = reject_; - }); - return { promise, resolve, reject }; -} - -// ../../node_modules/viem/_esm/utils/promise/createBatchScheduler.js -var schedulerCache = /* @__PURE__ */ new Map(); -function createBatchScheduler({ fn, id, shouldSplitBatch, wait = 0, sort }) { - const exec = async () => { - const scheduler = getScheduler(); - flush(); - const args = scheduler.map(({ args: args2 }) => args2); - if (args.length === 0) - return; - fn(args).then((data) => { - if (sort && Array.isArray(data)) - data.sort(sort); - for (let i = 0; i < scheduler.length; i++) { - const { resolve } = scheduler[i]; - resolve?.([data[i], data]); - } - }).catch((err) => { - for (let i = 0; i < scheduler.length; i++) { - const { reject } = scheduler[i]; - reject?.(err); - } - }); - }; - const flush = () => schedulerCache.delete(id); - const getBatchedArgs = () => getScheduler().map(({ args }) => args); - const getScheduler = () => schedulerCache.get(id) || []; - const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]); - return { - flush, - async schedule(args) { - const { promise, resolve, reject } = withResolvers(); - const split2 = shouldSplitBatch?.([...getBatchedArgs(), args]); - if (split2) - exec(); - const hasActiveScheduler = getScheduler().length > 0; - if (hasActiveScheduler) { - setScheduler({ args, resolve, reject }); - return promise; - } - setScheduler({ args, resolve, reject }); - setTimeout(exec, wait); - return promise; - } - }; -} - -// ../../node_modules/viem/_esm/utils/stateOverride.js -function serializeStateMapping(stateMapping) { - if (!stateMapping || stateMapping.length === 0) - return void 0; - return stateMapping.reduce((acc, { slot, value }) => { - if (slot.length !== 66) - throw new InvalidBytesLengthError({ - size: slot.length, - targetSize: 66, - type: "hex" - }); - if (value.length !== 66) - throw new InvalidBytesLengthError({ - size: value.length, - targetSize: 66, - type: "hex" - }); - acc[slot] = value; - return acc; - }, {}); -} -function serializeAccountStateOverride(parameters) { - const { balance, nonce, state, stateDiff, code } = parameters; - const rpcAccountStateOverride = {}; - if (code !== void 0) - rpcAccountStateOverride.code = code; - if (balance !== void 0) - rpcAccountStateOverride.balance = numberToHex(balance); - if (nonce !== void 0) - rpcAccountStateOverride.nonce = numberToHex(nonce); - if (state !== void 0) - rpcAccountStateOverride.state = serializeStateMapping(state); - if (stateDiff !== void 0) { - if (rpcAccountStateOverride.state) - throw new StateAssignmentConflictError(); - rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); - } - return rpcAccountStateOverride; -} -function serializeStateOverride(parameters) { - if (!parameters) - return void 0; - const rpcStateOverride = {}; - for (const { address, ...accountState } of parameters) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - if (rpcStateOverride[address]) - throw new AccountStateConflictError({ address }); - rpcStateOverride[address] = serializeAccountStateOverride(accountState); - } - return rpcStateOverride; -} - -// ../../node_modules/viem/_esm/constants/number.js -var maxInt8 = 2n ** (8n - 1n) - 1n; -var maxInt16 = 2n ** (16n - 1n) - 1n; -var maxInt24 = 2n ** (24n - 1n) - 1n; -var maxInt32 = 2n ** (32n - 1n) - 1n; -var maxInt40 = 2n ** (40n - 1n) - 1n; -var maxInt48 = 2n ** (48n - 1n) - 1n; -var maxInt56 = 2n ** (56n - 1n) - 1n; -var maxInt64 = 2n ** (64n - 1n) - 1n; -var maxInt72 = 2n ** (72n - 1n) - 1n; -var maxInt80 = 2n ** (80n - 1n) - 1n; -var maxInt88 = 2n ** (88n - 1n) - 1n; -var maxInt96 = 2n ** (96n - 1n) - 1n; -var maxInt104 = 2n ** (104n - 1n) - 1n; -var maxInt112 = 2n ** (112n - 1n) - 1n; -var maxInt120 = 2n ** (120n - 1n) - 1n; -var maxInt128 = 2n ** (128n - 1n) - 1n; -var maxInt136 = 2n ** (136n - 1n) - 1n; -var maxInt144 = 2n ** (144n - 1n) - 1n; -var maxInt152 = 2n ** (152n - 1n) - 1n; -var maxInt160 = 2n ** (160n - 1n) - 1n; -var maxInt168 = 2n ** (168n - 1n) - 1n; -var maxInt176 = 2n ** (176n - 1n) - 1n; -var maxInt184 = 2n ** (184n - 1n) - 1n; -var maxInt192 = 2n ** (192n - 1n) - 1n; -var maxInt200 = 2n ** (200n - 1n) - 1n; -var maxInt208 = 2n ** (208n - 1n) - 1n; -var maxInt216 = 2n ** (216n - 1n) - 1n; -var maxInt224 = 2n ** (224n - 1n) - 1n; -var maxInt232 = 2n ** (232n - 1n) - 1n; -var maxInt240 = 2n ** (240n - 1n) - 1n; -var maxInt248 = 2n ** (248n - 1n) - 1n; -var maxInt256 = 2n ** (256n - 1n) - 1n; -var minInt8 = -(2n ** (8n - 1n)); -var minInt16 = -(2n ** (16n - 1n)); -var minInt24 = -(2n ** (24n - 1n)); -var minInt32 = -(2n ** (32n - 1n)); -var minInt40 = -(2n ** (40n - 1n)); -var minInt48 = -(2n ** (48n - 1n)); -var minInt56 = -(2n ** (56n - 1n)); -var minInt64 = -(2n ** (64n - 1n)); -var minInt72 = -(2n ** (72n - 1n)); -var minInt80 = -(2n ** (80n - 1n)); -var minInt88 = -(2n ** (88n - 1n)); -var minInt96 = -(2n ** (96n - 1n)); -var minInt104 = -(2n ** (104n - 1n)); -var minInt112 = -(2n ** (112n - 1n)); -var minInt120 = -(2n ** (120n - 1n)); -var minInt128 = -(2n ** (128n - 1n)); -var minInt136 = -(2n ** (136n - 1n)); -var minInt144 = -(2n ** (144n - 1n)); -var minInt152 = -(2n ** (152n - 1n)); -var minInt160 = -(2n ** (160n - 1n)); -var minInt168 = -(2n ** (168n - 1n)); -var minInt176 = -(2n ** (176n - 1n)); -var minInt184 = -(2n ** (184n - 1n)); -var minInt192 = -(2n ** (192n - 1n)); -var minInt200 = -(2n ** (200n - 1n)); -var minInt208 = -(2n ** (208n - 1n)); -var minInt216 = -(2n ** (216n - 1n)); -var minInt224 = -(2n ** (224n - 1n)); -var minInt232 = -(2n ** (232n - 1n)); -var minInt240 = -(2n ** (240n - 1n)); -var minInt248 = -(2n ** (248n - 1n)); -var minInt256 = -(2n ** (256n - 1n)); -var maxUint8 = 2n ** 8n - 1n; -var maxUint16 = 2n ** 16n - 1n; -var maxUint24 = 2n ** 24n - 1n; -var maxUint32 = 2n ** 32n - 1n; -var maxUint40 = 2n ** 40n - 1n; -var maxUint48 = 2n ** 48n - 1n; -var maxUint56 = 2n ** 56n - 1n; -var maxUint64 = 2n ** 64n - 1n; -var maxUint72 = 2n ** 72n - 1n; -var maxUint80 = 2n ** 80n - 1n; -var maxUint88 = 2n ** 88n - 1n; -var maxUint96 = 2n ** 96n - 1n; -var maxUint104 = 2n ** 104n - 1n; -var maxUint112 = 2n ** 112n - 1n; -var maxUint120 = 2n ** 120n - 1n; -var maxUint128 = 2n ** 128n - 1n; -var maxUint136 = 2n ** 136n - 1n; -var maxUint144 = 2n ** 144n - 1n; -var maxUint152 = 2n ** 152n - 1n; -var maxUint160 = 2n ** 160n - 1n; -var maxUint168 = 2n ** 168n - 1n; -var maxUint176 = 2n ** 176n - 1n; -var maxUint184 = 2n ** 184n - 1n; -var maxUint192 = 2n ** 192n - 1n; -var maxUint200 = 2n ** 200n - 1n; -var maxUint208 = 2n ** 208n - 1n; -var maxUint216 = 2n ** 216n - 1n; -var maxUint224 = 2n ** 224n - 1n; -var maxUint232 = 2n ** 232n - 1n; -var maxUint240 = 2n ** 240n - 1n; -var maxUint248 = 2n ** 248n - 1n; -var maxUint256 = 2n ** 256n - 1n; - -// ../../node_modules/viem/_esm/utils/transaction/assertRequest.js -function assertRequest(args) { - const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args; - const account = account_ ? parseAccount(account_) : void 0; - if (account && !isAddress(account.address)) - throw new InvalidAddressError({ address: account.address }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) - throw new FeeConflictError(); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); -} - -// ../../node_modules/viem/_esm/actions/public/call.js -async function call(client, args) { - const { account: account_ = client.account, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = "latest", accessList, blobs, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, ...rest } = args; - const account = account_ ? parseAccount(account_) : void 0; - if (code && (factory || factoryData)) - throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); - if (code && to) - throw new BaseError2("Cannot provide both `code` & `to` as parameters."); - const deploylessCallViaBytecode = code && data_; - const deploylessCallViaFactory = factory && factoryData && to && data_; - const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; - const data = (() => { - if (deploylessCallViaBytecode) - return toDeploylessCallViaBytecodeData({ - code, - data: data_ - }); - if (deploylessCallViaFactory) - return toDeploylessCallViaFactoryData({ - data: data_, - factory, - factoryData, - to - }); - return data_; - })(); - try { - assertRequest(args); - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format = chainFormat || formatTransactionRequest; - const request = format({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - from: account?.address, - accessList, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to: deploylessCall ? void 0 : to, - value - }); - if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { - try { - return await scheduleMulticall(client, { - ...request, - blockNumber, - blockTag - }); - } catch (err) { - if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) - throw err; - } - } - const response = await client.request({ - method: "eth_call", - params: rpcStateOverride ? [ - request, - block, - rpcStateOverride - ] : [request, block] - }); - if (response === "0x") - return { data: void 0 }; - return { data: response }; - } catch (err) { - const data2 = getRevertErrorData(err); - const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-MMGH6DXX.js"); - if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to) - return { data: await offchainLookup2(client, { data: data2, to }) }; - if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") - throw new CounterfactualDeploymentFailedError({ factory }); - throw getCallError(err, { - ...args, - account, - chain: client.chain - }); - } -} -function shouldPerformMulticall({ request }) { - const { data, to, ...request_ } = request; - if (!data) - return false; - if (data.startsWith(aggregate3Signature)) - return false; - if (!to) - return false; - if (Object.values(request_).filter((x) => typeof x !== "undefined").length > 0) - return false; - return true; -} -async function scheduleMulticall(client, args) { - const { batchSize = 1024, wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to } = args; - let multicallAddress = multicallAddress_; - if (!multicallAddress) { - if (!client.chain) - throw new ClientChainNotConfiguredError(); - multicallAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "multicall3" - }); - } - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const { schedule } = createBatchScheduler({ - id: `${client.uid}.${block}`, - wait, - shouldSplitBatch(args2) { - const size2 = args2.reduce((size3, { data: data2 }) => size3 + (data2.length - 2), 0); - return size2 > batchSize * 2; - }, - fn: async (requests) => { - const calls = requests.map((request) => ({ - allowFailure: true, - callData: request.data, - target: request.to - })); - const calldata = encodeFunctionData({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3" - }); - const data2 = await client.request({ - method: "eth_call", - params: [ - { - data: calldata, - to: multicallAddress - }, - block - ] - }); - return decodeFunctionResult({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3", - data: data2 || "0x" - }); - } - }); - const [{ returnData, success }] = await schedule({ data, to }); - if (!success) - throw new RawContractError({ data: returnData }); - if (returnData === "0x") - return { data: void 0 }; - return { data: returnData }; -} -function toDeploylessCallViaBytecodeData(parameters) { - const { code, data } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(bytes, bytes)"]), - bytecode: deploylessCallViaBytecodeBytecode, - args: [code, data] - }); -} -function toDeploylessCallViaFactoryData(parameters) { - const { data, factory, factoryData, to } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(address, bytes, address, bytes)"]), - bytecode: deploylessCallViaFactoryBytecode, - args: [to, data, factory, factoryData] - }); -} -function getRevertErrorData(err) { - if (!(err instanceof BaseError2)) - return void 0; - const error = err.walk(); - return typeof error?.data === "object" ? error.data?.data : error.data; -} - -// ../../node_modules/viem/_esm/errors/ccip.js -var OffchainLookupError = class extends BaseError2 { - constructor({ callbackSelector, cause, data, extraData, sender, urls }) { - super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { - cause, - metaMessages: [ - ...cause.metaMessages || [], - cause.metaMessages?.length ? "" : [], - "Offchain Gateway Call:", - urls && [ - " Gateway URL(s):", - ...urls.map((url) => ` ${getUrl(url)}`) - ], - ` Sender: ${sender}`, - ` Data: ${data}`, - ` Callback selector: ${callbackSelector}`, - ` Extra data: ${extraData}` - ].flat(), - name: "OffchainLookupError" - }); - } -}; -var OffchainLookupResponseMalformedError = class extends BaseError2 { - constructor({ result, url }) { - super("Offchain gateway response is malformed. Response data must be a hex value.", { - metaMessages: [ - `Gateway URL: ${getUrl(url)}`, - `Response: ${stringify(result)}` - ], - name: "OffchainLookupResponseMalformedError" - }); - } -}; -var OffchainLookupSenderMismatchError = class extends BaseError2 { - constructor({ sender, to }) { - super("Reverted sender address does not match target contract address (`to`).", { - metaMessages: [ - `Contract address: ${to}`, - `OffchainLookup sender address: ${sender}` - ], - name: "OffchainLookupSenderMismatchError" - }); - } -}; - -// ../../node_modules/viem/_esm/utils/address/isAddressEqual.js -function isAddressEqual(a, b) { - if (!isAddress(a, { strict: false })) - throw new InvalidAddressError({ address: a }); - if (!isAddress(b, { strict: false })) - throw new InvalidAddressError({ address: b }); - return a.toLowerCase() === b.toLowerCase(); -} - -// ../../node_modules/viem/_esm/utils/ccip.js -var offchainLookupSignature = "0x556f1830"; -var offchainLookupAbiItem = { - name: "OffchainLookup", - type: "error", - inputs: [ - { - name: "sender", - type: "address" - }, - { - name: "urls", - type: "string[]" - }, - { - name: "callData", - type: "bytes" - }, - { - name: "callbackFunction", - type: "bytes4" - }, - { - name: "extraData", - type: "bytes" - } - ] -}; -async function offchainLookup(client, { blockNumber, blockTag, data, to }) { - const { args } = decodeErrorResult({ - data, - abi: [offchainLookupAbiItem] - }); - const [sender, urls, callData, callbackSelector, extraData] = args; - const { ccipRead } = client; - const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; - try { - if (!isAddressEqual(to, sender)) - throw new OffchainLookupSenderMismatchError({ sender, to }); - const result = await ccipRequest_({ data: callData, sender, urls }); - const { data: data_ } = await call(client, { - blockNumber, - blockTag, - data: concat([ - callbackSelector, - encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) - ]), - to - }); - return data_; - } catch (err) { - throw new OffchainLookupError({ - callbackSelector, - cause: err, - data, - extraData, - sender, - urls - }); - } -} -async function ccipRequest({ data, sender, urls }) { - let error = new Error("An unknown error occurred."); - for (let i = 0; i < urls.length; i++) { - const url = urls[i]; - const method = url.includes("{data}") ? "GET" : "POST"; - const body = method === "POST" ? { data, sender } : void 0; - const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; - try { - const response = await fetch(url.replace("{sender}", sender).replace("{data}", data), { - body: JSON.stringify(body), - headers, - method - }); - let result; - if (response.headers.get("Content-Type")?.startsWith("application/json")) { - result = (await response.json()).data; - } else { - result = await response.text(); - } - if (!response.ok) { - error = new HttpRequestError({ - body, - details: result?.error ? stringify(result.error) : response.statusText, - headers: response.headers, - status: response.status, - url - }); - continue; - } - if (!isHex(result)) { - error = new OffchainLookupResponseMalformedError({ - result, - url - }); - continue; - } - return result; - } catch (err) { - error = new HttpRequestError({ - body, - details: err.message, - url - }); - } - } - throw error; -} - -export { - aexists, - aoutput, - createView, - rotr, - toBytes2 as toBytes, - Hash, - wrapConstructor, - BaseError2 as BaseError, - isHex, - size, - trim, - toBytes as toBytes2, - hexToBytes, - hexToBigInt, - hexToNumber, - toHex, - bytesToHex, - numberToHex, - stringToHex, - InvalidAddressError, - keccak256, - checksumAddress, - isAddress, - concat, - concatHex, - createCursor, - InvalidLegacyVError, - InvalidSerializableTransactionError, - InvalidStorageKeySizeError, - maxUint256, - InvalidChainIdError, - FeeCapTooHighError, - TipAboveFeeCapError, - slice, - BytesSizeMismatchError, - bytesRegex2 as bytesRegex, - integerRegex2 as integerRegex, - encodeAbiParameters, - stringify, - offchainLookupSignature, - offchainLookupAbiItem, - offchainLookup, - ccipRequest -}; -/*! Bundled license information: - -@noble/hashes/esm/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=chunk-NTU6R7BC.js.map \ No newline at end of file diff --git a/dist/chunk-NTU6R7BC.js.map b/dist/chunk-NTU6R7BC.js.map deleted file mode 100644 index 07f42cc..0000000 --- a/dist/chunk-NTU6R7BC.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../node_modules/viem/node_modules/abitype/src/version.ts","../../../node_modules/viem/node_modules/abitype/src/errors.ts","../../../node_modules/viem/node_modules/abitype/src/regex.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiParameter.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiParameters.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/formatAbiItem.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/signatures.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/abiItem.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/abiParameter.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/signature.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/struct.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/errors/splitParameters.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/cache.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/utils.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/runtime/structs.ts","../../../node_modules/viem/node_modules/abitype/src/human-readable/parseAbi.ts","../../../node_modules/viem/accounts/utils/parseAccount.ts","../../../node_modules/viem/constants/abis.ts","../../../node_modules/viem/constants/contract.ts","../../../node_modules/viem/constants/contracts.ts","../../../node_modules/viem/errors/version.ts","../../../node_modules/viem/errors/base.ts","../../../node_modules/viem/errors/chain.ts","../../../node_modules/viem/constants/solidity.ts","../../../node_modules/viem/utils/abi/formatAbiItem.ts","../../../node_modules/viem/utils/data/isHex.ts","../../../node_modules/viem/utils/data/size.ts","../../../node_modules/viem/errors/abi.ts","../../../node_modules/viem/errors/data.ts","../../../node_modules/viem/utils/data/slice.ts","../../../node_modules/viem/utils/data/pad.ts","../../../node_modules/viem/errors/encoding.ts","../../../node_modules/viem/utils/data/trim.ts","../../../node_modules/viem/utils/encoding/fromHex.ts","../../../node_modules/viem/utils/encoding/toHex.ts","../../../node_modules/viem/utils/encoding/toBytes.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/viem/utils/hash/keccak256.ts","../../../node_modules/viem/utils/hash/hashSignature.ts","../../../node_modules/viem/utils/hash/normalizeSignature.ts","../../../node_modules/viem/utils/hash/toSignature.ts","../../../node_modules/viem/utils/hash/toSignatureHash.ts","../../../node_modules/viem/utils/hash/toFunctionSelector.ts","../../../node_modules/viem/errors/address.ts","../../../node_modules/viem/utils/lru.ts","../../../node_modules/viem/utils/address/isAddress.ts","../../../node_modules/viem/utils/address/getAddress.ts","../../../node_modules/viem/errors/cursor.ts","../../../node_modules/viem/utils/cursor.ts","../../../node_modules/viem/utils/encoding/fromBytes.ts","../../../node_modules/viem/utils/data/concat.ts","../../../node_modules/viem/utils/regex.ts","../../../node_modules/viem/utils/abi/encodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeAbiParameters.ts","../../../node_modules/viem/utils/abi/decodeErrorResult.ts","../../../node_modules/viem/utils/stringify.ts","../../../node_modules/viem/utils/hash/toEventSelector.ts","../../../node_modules/viem/utils/abi/getAbiItem.ts","../../../node_modules/viem/constants/unit.ts","../../../node_modules/viem/utils/unit/formatUnits.ts","../../../node_modules/viem/utils/unit/formatEther.ts","../../../node_modules/viem/utils/unit/formatGwei.ts","../../../node_modules/viem/errors/stateOverride.ts","../../../node_modules/viem/errors/transaction.ts","../../../node_modules/viem/errors/utils.ts","../../../node_modules/viem/errors/contract.ts","../../../node_modules/viem/utils/abi/decodeFunctionResult.ts","../../../node_modules/viem/utils/abi/encodeDeployData.ts","../../../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../../../node_modules/viem/utils/abi/encodeFunctionData.ts","../../../node_modules/viem/utils/chain/getChainContractAddress.ts","../../../node_modules/viem/errors/node.ts","../../../node_modules/viem/errors/request.ts","../../../node_modules/viem/utils/errors/getNodeError.ts","../../../node_modules/viem/utils/errors/getCallError.ts","../../../node_modules/viem/utils/formatters/extract.ts","../../../node_modules/viem/utils/formatters/transactionRequest.ts","../../../node_modules/viem/utils/promise/withResolvers.ts","../../../node_modules/viem/utils/promise/createBatchScheduler.ts","../../../node_modules/viem/utils/stateOverride.ts","../../../node_modules/viem/constants/number.ts","../../../node_modules/viem/utils/transaction/assertRequest.ts","../../../node_modules/viem/actions/public/call.ts","../../../node_modules/viem/errors/ccip.ts","../../../node_modules/viem/utils/address/isAddressEqual.ts","../../../node_modules/viem/utils/ccip.ts"],"sourcesContent":["export const version = '1.0.7'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n\n override name = 'AbiTypeError'\n\n constructor(shortMessage: string, args: BaseErrorArgs = {}) {\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 const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: abitype@${version}`,\n ].join('\\n')\n\n super(message)\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","// 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 type | 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 abiParameter - 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 abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter 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 [key in keyof components]: FormatAbiParameter<\n {\n type: components[key]['type']\n } & (IsNarrowable extends true\n ? { name: components[key]['name'] }\n : unknown) &\n (components[key] extends { components: readonly AbiParameter[] }\n ? { components: components[key]['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 : `${abiParameter['type']}${abiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${abiParameter['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 abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): 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 abiParameters - 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [key in keyof abiParameters]: 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: abiParameters): 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 {\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 abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem =\n Abi[number] extends abiItem\n ? string\n :\n | (abiItem extends AbiFunction\n ? AbiFunction extends abiItem\n ? string\n : `function ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${abiItem['stateMutability']}`\n : ''}${abiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters})`}`\n : never)\n | (abiItem extends AbiEvent\n ? AbiEvent extends abiItem\n ? string\n : `event ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiError\n ? AbiError extends abiItem\n ? string\n : `error ${AssertName}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiConstructor\n ? AbiConstructor extends abiItem\n ? string\n : `constructor(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiFallback\n ? AbiFallback extends abiItem\n ? string\n : `fallback() external${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiReceive\n ? AbiReceive extends abiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? abiParameters\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: abiItem,\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 if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n if (abiItem.type === 'fallback')\n return `fallback() external${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }` as Result\n return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n EventModifier,\n FunctionModifier,\n Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n errorSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)$/\nexport function isEventSignature(signature: string) {\n return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n return execTyped<{ name: string; parameters: string }>(\n eventSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?.*?)\\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n return execTyped<{\n name: string\n parameters: string\n stateMutability?: AbiStateMutability\n returns?: string\n }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?.*?)\\}$/\nexport function isStructSignature(signature: string) {\n return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n return execTyped<{ name: string; properties: string }>(\n structSignatureRegex,\n signature,\n )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n /^constructor\\((?.*?)\\)(?:\\s(?payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n return execTyped<{\n parameters: string\n stateMutability?: Extract\n }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex =\n /^fallback\\(\\) external(?:\\s(?payable{1}))?$/\nexport function isFallbackSignature(signature: string) {\n return fallbackSignatureRegex.test(signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set([\n 'memory',\n 'indexed',\n 'storage',\n 'calldata',\n])\nexport const eventModifiers = new Set(['indexed'])\nexport const functionModifiers = new Set([\n 'calldata',\n 'memory',\n 'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n override name = 'InvalidAbiItemError'\n\n constructor({ signature }: { signature: string | object }) {\n super('Failed to parse ABI item.', {\n details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n docsPath: '/api/human#parseabiitem-1',\n })\n }\n}\n\nexport class UnknownTypeError extends BaseError {\n override name = 'UnknownTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [\n `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n ],\n })\n }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n override name = 'UnknownSolidityTypeError'\n\n constructor({ type }: { type: string }) {\n super('Unknown type.', {\n metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n override name = 'InvalidAbiParameterError'\n\n constructor({ param }: { param: string | object }) {\n super('Failed to parse ABI parameter.', {\n details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n docsPath: '/api/human#parseabiparameter-1',\n })\n }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n override name = 'InvalidAbiParametersError'\n\n constructor({ params }: { params: string | object }) {\n super('Failed to parse ABI parameters.', {\n details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n docsPath: '/api/human#parseabiparameters-1',\n })\n }\n}\n\nexport class InvalidParameterError extends BaseError {\n override name = 'InvalidParameterError'\n\n constructor({ param }: { param: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n })\n }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n override name = 'SolidityProtectedKeywordError'\n\n constructor({ param, name }: { param: string; name: string }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n ],\n })\n }\n}\n\nexport class InvalidModifierError extends BaseError {\n override name = 'InvalidModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n ],\n })\n }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n override name = 'InvalidFunctionModifierError'\n\n constructor({\n param,\n type,\n modifier,\n }: {\n param: string\n type?: AbiItemType | 'struct' | undefined\n modifier: Modifier\n }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${\n type ? ` in \"${type}\" type` : ''\n }.`,\n `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n ],\n })\n }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n override name = 'InvalidAbiTypeParameterError'\n\n constructor({\n abiParameter,\n }: {\n abiParameter: AbiParameter & { indexed?: boolean | undefined }\n }) {\n super('Invalid ABI parameter.', {\n details: JSON.stringify(abiParameter, null, 2),\n metaMessages: ['ABI parameter type is invalid.'],\n })\n }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n override name = 'InvalidSignatureError'\n\n constructor({\n signature,\n type,\n }: {\n signature: string\n type: AbiItemType | 'struct'\n }) {\n super(`Invalid ${type} signature.`, {\n details: signature,\n })\n }\n}\n\nexport class UnknownSignatureError extends BaseError {\n override name = 'UnknownSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Unknown signature.', {\n details: signature,\n })\n }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n override name = 'InvalidStructSignatureError'\n\n constructor({ signature }: { signature: string }) {\n super('Invalid struct signature.', {\n details: signature,\n metaMessages: ['No properties exist.'],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n override name = 'CircularReferenceError'\n\n constructor({ type }: { type: string }) {\n super('Circular reference detected.', {\n metaMessages: [`Struct \"${type}\" is a circular reference.`],\n })\n }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n override name = 'InvalidParenthesisError'\n\n constructor({ current, depth }: { current: string; depth: number }) {\n super('Unbalanced parentheses.', {\n metaMessages: [\n `\"${current.trim()}\" has too many ${\n depth > 0 ? 'opening' : 'closing'\n } parentheses.`,\n ],\n details: `Depth \"${depth}\"`,\n })\n }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport type { StructLookup } from '../types/structs.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n param: string,\n type?: AbiItemType | 'struct',\n structs?: StructLookup,\n) {\n let structKey = ''\n if (structs)\n for (const struct of Object.entries(structs)) {\n if (!struct) continue\n let propertyKey = ''\n for (const property of struct[1]) {\n propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`\n }\n structKey += `(${struct[0]}{${propertyKey}})`\n }\n if (type) return `${type}:${param}${structKey}`\n return param\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n string,\n AbiParameter & { indexed?: boolean }\n>([\n // Unnamed\n ['address', { type: 'address' }],\n ['bool', { type: 'bool' }],\n ['bytes', { type: 'bytes' }],\n ['bytes32', { type: 'bytes32' }],\n ['int', { type: 'int256' }],\n ['int256', { type: 'int256' }],\n ['string', { type: 'string' }],\n ['uint', { type: 'uint256' }],\n ['uint8', { type: 'uint8' }],\n ['uint16', { type: 'uint16' }],\n ['uint24', { type: 'uint24' }],\n ['uint32', { type: 'uint32' }],\n ['uint64', { type: 'uint64' }],\n ['uint96', { type: 'uint96' }],\n ['uint112', { type: 'uint112' }],\n ['uint160', { type: 'uint160' }],\n ['uint192', { type: 'uint192' }],\n ['uint256', { type: 'uint256' }],\n\n // Named\n ['address owner', { type: 'address', name: 'owner' }],\n ['address to', { type: 'address', name: 'to' }],\n ['bool approved', { type: 'bool', name: 'approved' }],\n ['bytes _data', { type: 'bytes', name: '_data' }],\n ['bytes data', { type: 'bytes', name: 'data' }],\n ['bytes signature', { type: 'bytes', name: 'signature' }],\n ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n ['bytes32 r', { type: 'bytes32', name: 'r' }],\n ['bytes32 root', { type: 'bytes32', name: 'root' }],\n ['bytes32 s', { type: 'bytes32', name: 's' }],\n ['string name', { type: 'string', name: 'name' }],\n ['string symbol', { type: 'string', name: 'symbol' }],\n ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint8 v', { type: 'uint8', name: 'v' }],\n ['uint256 balance', { type: 'uint256', name: 'balance' }],\n ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint256 value', { type: 'uint256', name: 'value' }],\n\n // Indexed\n [\n 'event:address indexed from',\n { type: 'address', name: 'from', indexed: true },\n ],\n ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n [\n 'event:uint indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n [\n 'event:uint256 indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n])\n","import type {\n AbiItemType,\n AbiType,\n SolidityArray,\n SolidityBytes,\n SolidityString,\n SolidityTuple,\n} from '../../abi.js'\nimport {\n bytesRegex,\n execTyped,\n integerRegex,\n isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n eventModifiers,\n execConstructorSignature,\n execErrorSignature,\n execEventSignature,\n execFunctionSignature,\n functionModifiers,\n isConstructorSignature,\n isErrorSignature,\n isEventSignature,\n isFallbackSignature,\n isFunctionSignature,\n isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n if (isFunctionSignature(signature)) {\n const match = execFunctionSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n const inputParams = splitParameters(match.parameters)\n const inputs = []\n const inputLength = inputParams.length\n for (let i = 0; i < inputLength; i++) {\n inputs.push(\n parseAbiParameter(inputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n\n const outputs = []\n if (match.returns) {\n const outputParams = splitParameters(match.returns)\n const outputLength = outputParams.length\n for (let i = 0; i < outputLength; i++) {\n outputs.push(\n parseAbiParameter(outputParams[i]!, {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }),\n )\n }\n }\n\n return {\n name: match.name,\n type: 'function',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs,\n outputs,\n }\n }\n\n if (isEventSignature(signature)) {\n const match = execEventSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, {\n modifiers: eventModifiers,\n structs,\n type: 'event',\n }),\n )\n }\n return { name: match.name, type: 'event', inputs: abiParameters }\n }\n\n if (isErrorSignature(signature)) {\n const match = execErrorSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'error' }),\n )\n }\n return { name: match.name, type: 'error', inputs: abiParameters }\n }\n\n if (isConstructorSignature(signature)) {\n const match = execConstructorSignature(signature)\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n const params = splitParameters(match.parameters)\n const abiParameters = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n abiParameters.push(\n parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n )\n }\n return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n }\n }\n\n if (isFallbackSignature(signature)) return { type: 'fallback' }\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n }\n\n throw new UnknownSignatureError({ signature })\n}\n\nconst abiParameterWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n /^\\((?.+?)\\)(?(?:\\[\\d*?\\])+?)?(?:\\s(?calldata|indexed|memory|storage{1}))?(?:\\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n modifiers?: Set\n structs?: StructLookup\n type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n // optional namespace cache by `type`\n const parameterCacheKey = getParameterCacheKey(\n param,\n options?.type,\n options?.structs,\n )\n if (parameterCache.has(parameterCacheKey))\n return parameterCache.get(parameterCacheKey)!\n\n const isTuple = isTupleRegex.test(param)\n const match = execTyped<{\n array?: string\n modifier?: Modifier\n name?: string\n type: string\n }>(\n isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n param,\n )\n if (!match) throw new InvalidParameterError({ param })\n\n if (match.name && isSolidityKeyword(match.name))\n throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n const name = match.name ? { name: match.name } : {}\n const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n const structs = options?.structs ?? {}\n let type: string\n let components = {}\n if (isTuple) {\n type = 'tuple'\n const params = splitParameters(match.type)\n const components_ = []\n const length = params.length\n for (let i = 0; i < length; i++) {\n // remove `modifiers` from `options` to prevent from being added to tuple components\n components_.push(parseAbiParameter(params[i]!, { structs }))\n }\n components = { components: components_ }\n } else if (match.type in structs) {\n type = 'tuple'\n components = { components: structs[match.type] }\n } else if (dynamicIntegerRegex.test(match.type)) {\n type = `${match.type}256`\n } else {\n type = match.type\n if (!(options?.type === 'struct') && !isSolidityType(type))\n throw new UnknownSolidityTypeError({ type })\n }\n\n if (match.modifier) {\n // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n if (!options?.modifiers?.has?.(match.modifier))\n throw new InvalidModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n\n // Check if resolved `type` is valid if there is a function modifier\n if (\n functionModifiers.has(match.modifier as FunctionModifier) &&\n !isValidDataLocation(type, !!match.array)\n )\n throw new InvalidFunctionModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n })\n }\n\n const abiParameter = {\n type: `${type}${match.array ?? ''}`,\n ...name,\n ...indexed,\n ...components,\n }\n parameterCache.set(parameterCacheKey, abiParameter)\n return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n params: string,\n result: string[] = [],\n current = '',\n depth = 0,\n): readonly string[] {\n const length = params.trim().length\n // biome-ignore lint/correctness/noUnreachable: recursive\n for (let i = 0; i < length; i++) {\n const char = params[i]\n const tail = params.slice(i + 1)\n switch (char) {\n case ',':\n return depth === 0\n ? splitParameters(tail, [...result, current.trim()])\n : splitParameters(tail, result, `${current}${char}`, depth)\n case '(':\n return splitParameters(tail, result, `${current}${char}`, depth + 1)\n case ')':\n return splitParameters(tail, result, `${current}${char}`, depth - 1)\n default:\n return splitParameters(tail, result, `${current}${char}`, depth)\n }\n }\n\n if (current === '') return result\n if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n result.push(current.trim())\n return result\n}\n\nexport function isSolidityType(\n type: string,\n): type is Exclude {\n return (\n type === 'address' ||\n type === 'bool' ||\n type === 'function' ||\n type === 'string' ||\n bytesRegex.test(type) ||\n integerRegex.test(type)\n )\n}\n\nconst protectedKeywordsRegex =\n /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\n/** @internal */\nexport function isSolidityKeyword(name: string) {\n return (\n name === 'address' ||\n name === 'bool' ||\n name === 'function' ||\n name === 'string' ||\n name === 'tuple' ||\n bytesRegex.test(name) ||\n integerRegex.test(name) ||\n protectedKeywordsRegex.test(name)\n )\n}\n\n/** @internal */\nexport function isValidDataLocation(\n type: string,\n isArray: boolean,\n): type is Exclude<\n AbiType,\n SolidityString | Extract | SolidityArray\n> {\n return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n InvalidSignatureError,\n InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n const shallowStructs: StructLookup = {}\n const signaturesLength = signatures.length\n for (let i = 0; i < signaturesLength; i++) {\n const signature = signatures[i]!\n if (!isStructSignature(signature)) continue\n\n const match = execStructSignature(signature)\n if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n const properties = match.properties.split(';')\n\n const components: AbiParameter[] = []\n const propertiesLength = properties.length\n for (let k = 0; k < propertiesLength; k++) {\n const property = properties[k]!\n const trimmed = property.trim()\n if (!trimmed) continue\n const abiParameter = parseAbiParameter(trimmed, {\n type: 'struct',\n })\n components.push(abiParameter)\n }\n\n if (!components.length) throw new InvalidStructSignatureError({ signature })\n shallowStructs[match.name] = components\n }\n\n // Resolve nested structs inside each parameter\n const resolvedStructs: StructLookup = {}\n const entries = Object.entries(shallowStructs)\n const entriesLength = entries.length\n for (let i = 0; i < entriesLength; i++) {\n const [name, parameters] = entries[i]!\n resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n }\n\n return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n abiParameters: readonly (AbiParameter & { indexed?: true })[],\n structs: StructLookup,\n ancestors = new Set(),\n) {\n const components: AbiParameter[] = []\n const length = abiParameters.length\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i]!\n const isTuple = isTupleRegex.test(abiParameter.type)\n if (isTuple) components.push(abiParameter)\n else {\n const match = execTyped<{ array?: string; type: string }>(\n typeWithoutTupleRegex,\n abiParameter.type,\n )\n if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n const { array, type } = match\n if (type in structs) {\n if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n components.push({\n ...abiParameter,\n type: `tuple${array ?? ''}`,\n components: resolveStructs(\n structs[type] ?? [],\n structs,\n new Set([...ancestors, type]),\n ),\n })\n } else {\n if (isSolidityType(type)) components.push(abiParameter)\n else throw new UnknownTypeError({ type })\n }\n }\n }\n\n return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Error, Filter } from '../types.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * type Result = ParseAbi<\n * // ^? type Result = readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * [\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ]\n * >\n */\nexport type ParseAbi =\n string[] extends signatures\n ? Abi // If `T` was not able to be inferred (e.g. just `string[]`), return `Abi`\n : signatures extends readonly string[]\n ? signatures extends Signatures // Validate signatures\n ? ParseStructs extends infer sructs\n ? {\n [key in keyof signatures]: signatures[key] extends string\n ? ParseSignature\n : never\n } extends infer mapped extends readonly unknown[]\n ? Filter extends infer result\n ? result extends readonly []\n ? never\n : result\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n * // ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi(\n signatures: signatures['length'] extends 0\n ? Error<'At least one signature required'>\n : Signatures extends signatures\n ? signatures\n : Signatures,\n): ParseAbi {\n const structs = parseStructs(signatures as readonly string[])\n const abi = []\n const length = signatures.length as number\n for (let i = 0; i < length; i++) {\n const signature = (signatures as readonly string[])[i]!\n if (isStructSignature(signature)) continue\n abi.push(parseSignature(signature, structs))\n }\n return abi as unknown as ParseAbi\n}\n","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(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\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 {\n inputs: [],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n components: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'errors',\n type: 'tuple[]',\n },\n ],\n name: 'HttpError',\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 {\n name: 'resolve',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n { name: 'gateways', type: 'string[]' },\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 {\n name: 'reverse',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'string[]', name: 'gateways' },\n ],\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\n/** @internal */\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 name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n] as const\n\n/** [ERC-20 Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) */\nexport const erc20Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/**\n * [bytes32-flavored ERC-20](https://docs.makerdao.com/smart-contract-modules/mkr-module#4.-gotchas-potential-source-of-user-error)\n * for tokens (ie. Maker) that use bytes32 instead of string.\n */\nexport const erc20Abi_bytes32 = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n] as const\n\n/** [ERC-721 Non-Fungible Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) */\nexport const erc721Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'ApprovalForAll',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n name: 'approved',\n type: 'bool',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'getApproved',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'isApprovedForAll',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'operator',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'ownerOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'id',\n type: 'uint256',\n },\n {\n name: 'data',\n type: 'bytes',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'setApprovalForAll',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'operator',\n type: 'address',\n },\n {\n name: 'approved',\n type: 'bool',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenURI',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'tokeId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n] as const\n\n/** [ERC-4626 Tokenized Vaults Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-4626) */\nexport const erc4626Abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Deposit',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n name: 'allowance',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'approve',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'asset',\n outputs: [\n {\n name: 'assetTokenAddress',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'convertToAssets',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'convertToShares',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'deposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxDeposit',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxMint',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxRedeem',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxWithdraw',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'mint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewDeposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewMint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewRedeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewWithdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'redeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalAssets',\n outputs: [\n {\n name: 'totalManagedAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transfer',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transferFrom',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'withdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","export const aggregate3Signature = '0x82ad56cb'\n","export const deploylessCallViaBytecodeBytecode =\n '0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe'\n\nexport const deploylessCallViaFactoryBytecode =\n '0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe'\n\nexport const universalSignatureValidatorByteCode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n","export const version = '2.21.58'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\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(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (\n err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined\n )\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 constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint | undefined\n chain: Chain\n contract: { name: string; blockCreated?: number | undefined }\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 name: 'ChainDoesNotSupportContract',\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\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 name: 'ChainMismatchError',\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\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 name: 'ChainNotFoundError',\n },\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n })\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n { name: 'InvalidChainIdError' },\n )\n }\n}\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: 'Arithmetic 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","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 | undefined } = {},\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 | undefined } = {},\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 { 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 | undefined } = {},\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 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 type { Abi, 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 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 name: 'AbiConstructorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\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 name: 'AbiConstructorParamsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\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 {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\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 name: 'AbiDecodingDataSizeTooSmallError',\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 constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n })\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingArrayLengthMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\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 { name: 'AbiEncodingBytesSizeMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingLengthMismatchError' },\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\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 name: 'AbiErrorInputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(\n errorName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiErrorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\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 name: 'AbiErrorSignatureNotFoundError',\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\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 name: 'AbiEventSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(\n eventName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiEventNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(\n functionName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiFunctionNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\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 name: 'AbiFunctionOutputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\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 name: 'AbiFunctionSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(\n x: { abiItem: Abi[number]; type: string },\n y: { abiItem: Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n })\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n })\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\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 name: 'DecodeLogDataMismatch',\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 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 { name: 'DecodeLogTopicsMismatch' },\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\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, name: 'InvalidAbiEncodingType' },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\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, name: 'InvalidAbiDecodingType' },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n })\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\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 { name: 'InvalidDefinitionTypeError' },\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\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 { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\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 { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\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()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\n )\n }\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 = value 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: value,\n start?: number | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined) {\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(\n value: Hex | ByteArray,\n start?: number | undefined,\n end?: number | undefined,\n) {\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 {\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' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: value,\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 { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\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 { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\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 name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\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 { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim(\n hexOrBytes: value,\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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to 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\n * - Example: https://viem.sh/docs/utilities/fromHex#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 to 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 | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 | undefined\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#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#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 | undefined\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#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 {\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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toHex#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 | undefined\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#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 | undefined\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#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 | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\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#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: bigint | number | undefined\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${(\n signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : 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 | undefined\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#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 { 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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toBytes#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 | undefined\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#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 | undefined\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#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#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(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\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#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","function anumber(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction ahash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\nfunction aexists(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 aoutput(out: any, instance: any) {\n abytes(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 { anumber, anumber as number, abytes, abytes as bytes, ahash, aexists, aoutput };\n\nconst assert = {\n number: anumber,\n bytes: abytes,\n hash: ahash,\n exists: aexists,\n output: aoutput,\n};\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n// TODO: re-check https://issues.chromium.org/issues/42212588\n\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\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// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\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 abytes(bytes);\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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 hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\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\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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 // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { abytes, aexists, anumber, aoutput } 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 isLE,\n byteSwap32,\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: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: 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 anumber(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 if (!isLE) byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE) byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input) {\n aexists(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 aexists(this, false);\n abytes(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 anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array) {\n aoutput(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 | (to extends 'bytes' ? ByteArray : never)\n | (to 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_?: to | undefined,\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 ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport function hashSignature(sig: string) {\n return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype 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 AbiEvent, 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 ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n const def_ = (() => {\n if (typeof def === 'string') return def\n return formatAbiItem(def)\n })()\n return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n | HashSignatureErrorType\n | ToSignatureErrorType\n | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n return hashSignature(toSignature(fn))\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToFunctionSelectorErrorType =\n | ToSignatureHashErrorType\n | SliceErrorType\n | ErrorType\n\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn: string | AbiFunction) =>\n slice(toSignatureHash(fn), 0, 4)\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\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 { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap
    (8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\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 const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n })\n }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n { name: 'PositionOutOfBoundsError' },\n )\n }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n RecursiveReadLimitExceededError & {\n name: 'RecursiveReadLimitExceededError'\n }\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n { name: 'RecursiveReadLimitExceededError' },\n )\n }\n}\n","import {\n NegativeOffsetError,\n type NegativeOffsetErrorType,\n PositionOutOfBoundsError,\n type PositionOutOfBoundsErrorType,\n RecursiveReadLimitExceededError,\n type RecursiveReadLimitExceededErrorType,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n bytes: ByteArray\n dataView: DataView\n position: number\n positionReadCount: Map\n recursiveReadCount: number\n recursiveReadLimit: number\n remaining: number\n assertReadLimit(position?: number): void\n assertPosition(position: number): void\n decrementPosition(offset: number): void\n getReadCount(position?: number): number\n incrementPosition(offset: number): void\n inspectByte(position?: number): ByteArray[number]\n inspectBytes(length: number, position?: number): ByteArray\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: ByteArray[number]): void\n pushBytes(bytes: ByteArray): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): ByteArray[number]\n readBytes(length: number, size?: number): ByteArray\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\n\ntype CursorErrorType =\n | CursorAssertPositionErrorType\n | CursorDecrementPositionErrorType\n | CursorIncrementPositionErrorType\n | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetError | ErrorType\n\ntype StaticCursorErrorType =\n | NegativeOffsetErrorType\n | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n })\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n })\n },\n decrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position - offset\n this.assertPosition(position)\n this.position = position\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0\n },\n incrementPosition(offset) {\n if (offset < 0) throw new NegativeOffsetError({ offset })\n const position = this.position + offset\n this.assertPosition(position)\n this.position = position\n },\n inspectByte(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + length - 1)\n return this.bytes.subarray(position, position + length)\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position)\n return this.bytes[position]\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 1)\n return this.dataView.getUint16(position)\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 2)\n return (\n (this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2)\n )\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position\n this.assertPosition(position + 3)\n return this.dataView.getUint32(position)\n },\n pushByte(byte: ByteArray[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: ByteArray) {\n this.assertPosition(this.position + bytes.length - 1)\n this.bytes.set(bytes, this.position)\n this.position += bytes.length\n },\n pushUint8(value: number) {\n this.assertPosition(this.position)\n this.bytes[this.position] = value\n this.position++\n },\n pushUint16(value: number) {\n this.assertPosition(this.position + 1)\n this.dataView.setUint16(this.position, value)\n this.position += 2\n },\n pushUint24(value: number) {\n this.assertPosition(this.position + 2)\n this.dataView.setUint16(this.position, value >> 8)\n this.dataView.setUint8(this.position + 2, value & ~4294967040)\n this.position += 3\n },\n pushUint32(value: number) {\n this.assertPosition(this.position + 3)\n this.dataView.setUint32(this.position, value)\n this.position += 4\n },\n readByte() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectByte()\n this.position++\n return value\n },\n readBytes(length, size) {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectBytes(length)\n this.position += size ?? length\n return value\n },\n readUint8() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint8()\n this.position += 1\n return value\n },\n readUint16() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint16()\n this.position += 2\n return value\n },\n readUint24() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint24()\n this.position += 3\n return value\n },\n readUint32() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint32()\n this.position += 4\n return value\n },\n get remaining() {\n return this.bytes.length - this.position\n },\n setPosition(position) {\n const oldPosition = this.position\n this.assertPosition(position)\n this.position = position\n return () => (this.position = oldPosition)\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n const count = this.getReadCount()\n this.positionReadCount.set(this.position, count + 1)\n if (count > 0) this.recursiveReadCount++\n },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n | CursorErrorType\n | StaticCursorErrorType\n | ErrorType\n\nexport function createCursor(\n bytes: ByteArray,\n { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n type AssertSizeErrorType,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n assertSize,\n hexToBigInt,\n hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n | to\n | {\n /** Size of the bytes. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromBytesReturnType = to extends 'string'\n ? string\n : to extends 'hex'\n ? Hex\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromBytesErrorType =\n | BytesToHexErrorType\n | BytesToBigIntErrorType\n | BytesToBoolErrorType\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n bytes: ByteArray,\n toOrOpts: FromBytesParameters,\n): FromBytesReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number')\n return bytesToNumber(bytes, opts) as FromBytesReturnType\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts) as FromBytesReturnType\n if (to === 'boolean')\n return bytesToBool(bytes, opts) as FromBytesReturnType\n if (to === 'string')\n return bytesToString(bytes, opts) as FromBytesReturnType\n return bytesToHex(bytes, opts) as FromBytesReturnType\n}\n\nexport type BytesToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n | BytesToHexErrorType\n | HexToBigIntErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n bytes: ByteArray,\n opts: BytesToBigIntOpts = {},\n): bigint {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n bytes_: ByteArray,\n opts: BytesToBoolOpts = {},\n): boolean {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes)\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes)\n return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n | BytesToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n bytes: ByteArray,\n opts: BytesToNumberOpts = {},\n): number {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n bytes_: ByteArray,\n opts: BytesToStringOpts = {},\n): string {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat(\n values: readonly value[],\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","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\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","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 { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.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'\nimport { integerRegex } from '../regex.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 *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: params,\n values: params 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 as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values: values as any,\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\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams({\n params,\n values,\n}: {\n params: params\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\ntype PrepareParamErrorType =\n | EncodeAddressErrorType\n | EncodeArrayErrorType\n | EncodeBytesErrorType\n | EncodeBoolErrorType\n | EncodeNumberErrorType\n | EncodeStringErrorType\n | EncodeTupleErrorType\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam({\n param,\n value,\n}: {\n param: param\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 const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\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\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | 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\ntype 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\ntype EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray(\n value: AbiParameterToPrimitiveType,\n {\n length,\n param,\n }: {\n length: number | null\n param: param\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\ntype EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes(\n value: Hex,\n { param }: { param: param },\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 !== Number.parseInt(paramSize))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n if (typeof value !== 'boolean')\n throw new BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\ntype 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\ntype EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType,\n { param }: { param: param },\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\ntype 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 { AbiParameter, AbiParametersToPrimitiveTypes } from 'abitype'\n\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type BytesToBigIntErrorType,\n type BytesToBoolErrorType,\n type BytesToNumberErrorType,\n type BytesToStringErrorType,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n params extends readonly AbiParameter[] ? params : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | DecodeParameterErrorType\n | SizeErrorType\n | CreateCursorErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const params extends readonly AbiParameter[],\n>(\n params: params,\n data: ByteArray | Hex,\n): DecodeAbiParametersReturnType {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data\n const cursor = createCursor(bytes)\n\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n\n let consumed = 0\n const values = []\n for (let i = 0; i < params.length; ++i) {\n const param = params[i]\n cursor.setPosition(consumed)\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n })\n consumed += consumed_\n values.push(data)\n }\n return values as DecodeAbiParametersReturnType\n}\n\ntype DecodeParameterErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeStringErrorType\n | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n if (param.type === 'address') return decodeAddress(cursor)\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | BytesToHexErrorType\n | SliceBytesErrorType\n | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n const value = cursor.readBytes(32)\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n cursor: Cursor,\n param: AbiParameter,\n { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 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 // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n | BytesToNumberErrorType\n | BytesToHexErrorType\n | ErrorType\n\nfunction decodeBytes(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [bytesToHex(data), 32]\n }\n\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size), 32))\n return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n | BytesToNumberErrorType\n | BytesToBigIntErrorType\n | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256')\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n cursor: Cursor,\n param: TupleAbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\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 // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\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 [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(\n cursor: Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = bytesToString(trim(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\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 } 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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n ContractErrorArgs,\n ContractErrorName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { slice } from '../data/slice.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = { abi?: abi | undefined; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allErrorNames extends ContractErrorName = ContractErrorName,\n> = IsNarrowable extends true\n ? UnionEvaluate<\n {\n [errorName in allErrorNames]: {\n abiItem: abi extends Abi\n ? Abi extends abi\n ? AbiItem\n : ExtractAbiError\n : AbiItem\n args: ContractErrorArgs\n errorName: errorName\n }\n }[allErrorNames]\n >\n : {\n abiItem: AbiItem\n args: readonly unknown[] | undefined\n errorName: string\n }\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult(\n parameters: DecodeErrorResultParameters,\n): DecodeErrorResultReturnType {\n const { abi, data } = parameters as DecodeErrorResultParameters\n\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...(abi || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args:\n 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType\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 type { ErrorType } from '../../errors/utils.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport {\n AbiItemAmbiguityError,\n type AbiItemAmbiguityErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ExtractAbiItemForArgs,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nexport type GetAbiItemParameters<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n ///\n allArgs = AbiItemArgs,\n allNames = AbiItemName,\n> = {\n abi: abi\n name:\n | allNames // show all options\n | (name extends allNames ? name : never) // infer value\n | Hex // function selector\n} & UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | ToFunctionSelectorErrorType\n | AbiItemAmbiguityErrorType\n | ErrorType\n\nexport type GetAbiItemReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName = AbiItemName,\n args extends AbiItemArgs | undefined = AbiItemArgs,\n> = abi extends Abi\n ? Abi extends abi\n ? AbiItem | undefined\n : ExtractAbiItemForArgs<\n abi,\n name,\n args extends AbiItemArgs ? args : AbiItemArgs\n >\n : AbiItem | undefined\n\nexport function getAbiItem<\n const abi extends Abi | readonly unknown[],\n name extends AbiItemName,\n const args extends AbiItemArgs | undefined = undefined,\n>(\n parameters: GetAbiItemParameters,\n): GetAbiItemReturnType {\n const { abi, args = [], name } = parameters as unknown as GetAbiItemParameters\n\n const isSelector = isHex(name, { strict: false })\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return toEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0)\n return undefined as GetAbiItemReturnType\n if (abiItems.length === 1)\n return abiItems[0] as GetAbiItemReturnType\n\n let matchedAbiItem: AbiItem | undefined = undefined\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)\n return abiItem as GetAbiItemReturnType\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.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, abiParameter)\n })\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (\n matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs\n ) {\n const ambiguousTypes = getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AbiItemAmbiguityError(\n {\n abiItem,\n type: ambiguousTypes[0],\n },\n {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1],\n },\n )\n }\n\n matchedAbiItem = abiItem\n }\n }\n\n if (matchedAbiItem)\n return matchedAbiItem as GetAbiItemReturnType\n return abiItems[0] as GetAbiItemReturnType\n}\n\ntype IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\n/** @internal */\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, { strict: false })\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\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameter[],\n targetParameters: readonly AbiParameter[],\n args: AbiItemArgs,\n): AbiParameter['type'][] | undefined {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex]\n const targetParameter = targetParameters[parameterIndex]\n\n if (\n sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter\n )\n return getAmbiguousTypes(\n sourceParameter.components,\n targetParameter.components,\n (args as any)[parameterIndex],\n )\n\n const types = [sourceParameter.type, targetParameter.type]\n\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20')) return true\n if (types.includes('address') && types.includes('string'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\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 { 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\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","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\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\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 { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { BaseError } from './base.js'\n\nexport type AccountStateConflictErrorType = AccountStateConflictError & {\n name: 'AccountStateConflictError'\n}\n\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n })\n }\n}\n\nexport type StateAssignmentConflictErrorType = StateAssignmentConflictError & {\n name: 'StateAssignmentConflictError'\n}\n\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n })\n }\n}\n\n/** @internal */\nexport function prettyStateMapping(stateMapping: StateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`\n }, '')\n}\n\nexport function prettyStateOverride(stateOverride: StateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`\n if (state.nonce) val += ` nonce: ${state.nonce}\\n`\n if (state.balance) val += ` balance: ${state.balance}\\n`\n if (state.code) val += ` code: ${state.code}\\n`\n if (state.state) {\n val += ' state:\\n'\n val += prettyStateMapping(state.state)\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n'\n val += prettyStateMapping(state.stateDiff)\n }\n return val\n }, ' State Override:\\n')\n .slice(0, -1)\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 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 { name: 'FeeConflictError' },\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n })\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\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 '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n })\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\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 name: 'InvalidSerializedTransactionError',\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 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 { name: 'InvalidStorageKeySizeError' },\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'TransactionExecutionError',\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n blockTag?: BlockTag | undefined\n hash?: Hash | undefined\n index?: number | undefined\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 name: 'TransactionNotFoundError',\n })\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\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 name: 'TransactionReceiptNotFoundError',\n },\n )\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n { name: 'WaitForTransactionReceiptTimeoutError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nexport type ErrorType = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\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 { prettyStateOverride } from './stateOverride.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 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 stateOverride,\n }: CallParameters & {\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n let 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 if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`\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 name: 'CallExecutionError',\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[] | undefined\n override cause: BaseError\n contractAddress?: Address | undefined\n formattedArgs?: string | undefined\n functionName: string\n sender?: Address | undefined\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 | undefined\n contractAddress?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\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 prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'ContractFunctionExecutionError',\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 data?: DecodeErrorResultReturnType | undefined\n reason?: string | undefined\n signature?: Hex | undefined\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: {\n abi: Abi\n data?: Hex | undefined\n functionName: string\n message?: string | undefined\n }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined = undefined\n let metaMessages: string[] | undefined\n let reason: string | undefined\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 name: 'ContractFunctionRevertedError',\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 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 name: 'ContractFunctionZeroDataError',\n })\n }\n}\n\nexport type CounterfactualDeploymentFailedErrorType =\n CounterfactualDeploymentFailedError & {\n name: 'CounterfactualDeploymentFailedError'\n }\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }: { factory?: Address | undefined }) {\n super(\n `Deployment for counterfactual contract call failed${\n factory ? ` for factory \"${factory}\".` : ''\n }`,\n {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n },\n )\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n\n data?: Hex | { data?: Hex | undefined } | undefined\n\n constructor({\n data,\n message,\n }: {\n data?: Hex | { data?: Hex | undefined } | undefined\n message?: string | undefined\n }) {\n super(message || '', { name: 'RawContractError' })\n this.data = data\n }\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n AbiFunctionOutputsNotFoundError,\n type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n data: Hex\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | undefined }\n : { functionName: functionName | allFunctionNames }\n : { functionName?: functionName | allFunctionNames | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type DecodeFunctionResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n> = ContractFunctionReturnType<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName,\n args\n>\n\nexport type DecodeFunctionResultErrorType =\n | AbiFunctionNotFoundErrorType\n | AbiFunctionOutputsNotFoundErrorType\n | DecodeAbiParametersErrorType\n | GetAbiItemErrorType\n | ErrorType\n\nexport function decodeFunctionResult<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n const args extends ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n > = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n>(\n parameters: DecodeFunctionResultParameters,\n): DecodeFunctionResultReturnType {\n const { abi, args, functionName, data } =\n parameters as DecodeFunctionResultParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({ abi, args, name: functionName })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\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)\n return values as DecodeFunctionResultReturnType\n if (values && values.length === 1)\n return values[0] as DecodeFunctionResultReturnType\n return undefined as DecodeFunctionResultReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n hasConstructor = abi extends Abi\n ? Abi extends abi\n ? true\n : [Extract] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractConstructorArgs,\n> = {\n abi: abi\n bytecode: Hex\n} & UnionEvaluate<\n hasConstructor extends false\n ? { args?: undefined }\n : readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n>\n\nexport type EncodeDeployDataReturnType = Hex\n\nexport type EncodeDeployDataErrorType =\n | AbiConstructorNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | ErrorType\n\nexport function encodeDeployData(\n parameters: EncodeDeployDataParameters,\n): EncodeDeployDataReturnType {\n const { abi, args, bytecode } = parameters as EncodeDeployDataParameters\n if (!args || args.length === 0) return bytecode\n\n const description = abi.find((x) => 'type' in x && x.type === 'constructor')\n if (!description) throw new AbiConstructorNotFoundError({ docsPath })\n if (!('inputs' in description))\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n if (!description.inputs || description.inputs.length === 0)\n throw new AbiConstructorParamsNotFoundError({ docsPath })\n\n const data = encodeAbiParameters(description.inputs, args)\n return concatHex([bytecode, data!])\n}\n","import type {\n Abi,\n AbiStateMutability,\n ExtractAbiFunction,\n ExtractAbiFunctions,\n} from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionData'\n\nexport type PrepareEncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<{ args?: allArgs | undefined }> &\n (hasFunctions extends true ? unknown : never)\n\nexport type PrepareEncodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | undefined = ContractFunctionName,\n> = {\n abi: abi extends Abi\n ? functionName extends ContractFunctionName\n ? [ExtractAbiFunction]\n : abi\n : Abi\n functionName: Hex\n}\n\nexport type PrepareEncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function prepareEncodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: PrepareEncodeFunctionDataParameters,\n): PrepareEncodeFunctionDataReturnType {\n const { abi, args, functionName } =\n parameters as PrepareEncodeFunctionDataParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n } as unknown as PrepareEncodeFunctionDataReturnType\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport type { AbiFunctionNotFoundErrorType } from '../../errors/abi.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport type { FormatAbiItemErrorType } from './formatAbiItem.js'\nimport type { GetAbiItemErrorType } from './getAbiItem.js'\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js'\n\nexport type EncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName\n | Hex\n | undefined = ContractFunctionName,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName\n ? functionName\n : ContractFunctionName\n >,\n allFunctionNames = ContractFunctionName,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionDataReturnType = Hex\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName | undefined = undefined,\n>(\n parameters: EncodeFunctionDataParameters,\n): EncodeFunctionDataReturnType {\n const { args } = parameters as EncodeFunctionDataParameters\n\n const { abi, functionName } = (() => {\n if (\n parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x')\n )\n return parameters as { abi: Abi; functionName: Hex }\n return prepareEncodeFunctionData(parameters)\n })()\n\n const abiItem = abi[0]\n const signature = functionName\n\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\n : undefined\n return concatHex([signature, data ?? '0x'])\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 | undefined\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 { 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 constructor({\n cause,\n message,\n }: { cause?: BaseError | undefined; message?: string | undefined } = {}) {\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 name: 'ExecutionRevertedError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooHighError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooLowError',\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause, name: 'NonceTooHighError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\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, name: 'NonceTooLowError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause, name: 'NonceMaxValueError' },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage =\n /insufficient funds|exceeds transaction sender account balance/\n constructor({ cause }: { cause?: BaseError | undefined } = {}) {\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 name: 'InsufficientFundsError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\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 name: 'IntrinsicGasTooHighError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n name: 'IntrinsicGasTooLowError',\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 constructor({ cause }: { cause?: BaseError | undefined }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\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 constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\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 name: 'TipAboveFeeCapError',\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }: { cause?: BaseError | undefined }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\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 body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\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 constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; data?: unknown; 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 name: 'RpcRequestError',\n })\n this.code = error.code\n this.data = error.data\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\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 name: 'TimeoutError',\n })\n }\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'\nimport type { ExactPartial } from '../../types/utils.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 = ExactPartial<\n SendTransactionParameters\n>\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 =\n err instanceof BaseError\n ? err.walk(\n (e) =>\n (e as { code: number } | null | undefined)?.code ===\n ExecutionRevertedError.code,\n )\n : err\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\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 { 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 | undefined\n docsPath?: string | undefined\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","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'] | undefined },\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 { AuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { bytesToHex, numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n chain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n request: ExactPartial,\n) {\n const rpcRequest = {} as RpcTransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(\n request.authorizationList,\n )\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = (request.blobs as ByteArray[]).map((x) =>\n bytesToHex(x),\n )\n else rpcRequest.blobs = request.blobs\n }\n if (typeof request.data !== 'undefined') rpcRequest.data = request.data\n if (typeof request.from !== 'undefined') rpcRequest.from = request.from\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce)\n if (typeof request.to !== 'undefined') rpcRequest.to = request.to\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type]\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value)\n\n return rpcRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: AuthorizationList,\n): RpcAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n address: authorization.contractAddress,\n r: authorization.r,\n s: authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }) as any,\n ) as RpcAuthorizationList\n}\n","/** @internal */\nexport type PromiseWithResolvers = {\n promise: Promise\n resolve: (value: type | PromiseLike) => void\n reject: (reason?: unknown) => void\n}\n\n/** @internal */\nexport function withResolvers(): PromiseWithResolvers {\n let resolve: PromiseWithResolvers['resolve'] = () => undefined\n let reject: PromiseWithResolvers['reject'] = () => undefined\n\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_\n reject = reject_\n })\n\n return { promise, resolve, reject }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type PromiseWithResolvers, withResolvers } from './withResolvers.js'\n\ntype Resolved = [\n result: returnType[number],\n results: returnType,\n]\n\ntype SchedulerItem = {\n args: unknown\n resolve: PromiseWithResolvers['resolve']\n reject: PromiseWithResolvers['reject']\n}\n\ntype BatchResultsCompareFn = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise>\n : (args: parameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\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 parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i]\n resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i]\n reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\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: parameters) {\n const { promise, resolve, reject } = withResolvers()\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, resolve, reject })\n return promise\n }\n\n setScheduler({ args, resolve, reject })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n InvalidBytesLengthError,\n type InvalidBytesLengthErrorType,\n} from '../errors/data.js'\nimport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from '../errors/stateOverride.js'\nimport type {\n RpcAccountStateOverride,\n RpcStateMapping,\n RpcStateOverride,\n} from '../types/rpc.js'\nimport type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { isAddress } from './address/isAddress.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\n\ntype SerializeStateMappingParameters = StateMapping | undefined\n\ntype SerializeStateMappingErrorType = InvalidBytesLengthErrorType\n\n/** @internal */\nexport function serializeStateMapping(\n stateMapping: SerializeStateMappingParameters,\n): RpcStateMapping | undefined {\n if (!stateMapping || stateMapping.length === 0) return undefined\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n })\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n })\n acc[slot] = value\n return acc\n }, {} as RpcStateMapping)\n}\n\ntype SerializeAccountStateOverrideParameters = Omit<\n StateOverride[number],\n 'address'\n>\n\ntype SerializeAccountStateOverrideErrorType =\n | NumberToHexErrorType\n | StateAssignmentConflictErrorType\n | SerializeStateMappingErrorType\n\n/** @internal */\nexport function serializeAccountStateOverride(\n parameters: SerializeAccountStateOverrideParameters,\n): RpcAccountStateOverride {\n const { balance, nonce, state, stateDiff, code } = parameters\n const rpcAccountStateOverride: RpcAccountStateOverride = {}\n if (code !== undefined) rpcAccountStateOverride.code = code\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance)\n if (nonce !== undefined) rpcAccountStateOverride.nonce = numberToHex(nonce)\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state)\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state) throw new StateAssignmentConflictError()\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff)\n }\n return rpcAccountStateOverride\n}\n\ntype SerializeStateOverrideParameters = StateOverride | undefined\n\nexport type SerializeStateOverrideErrorType =\n | InvalidAddressErrorType\n | AccountStateConflictErrorType\n | SerializeAccountStateOverrideErrorType\n\n/** @internal */\nexport function serializeStateOverride(\n parameters?: SerializeStateOverrideParameters,\n): RpcStateOverride | undefined {\n if (!parameters) return undefined\n const rpcStateOverride: RpcStateOverride = {}\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address })\n rpcStateOverride[address] = serializeAccountStateOverride(accountState)\n }\n return rpcStateOverride\n}\n","export const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { maxUint256 } from '../../constants/number.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 type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = ExactPartial<\n SendTransactionParameters\n>\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 > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import { type Address, parseAbi } 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 {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n} from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ChainDoesNotSupportContract,\n ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n CounterfactualDeploymentFailedError,\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 { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.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 {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type CallParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n /** Whether or not to enable multicall batching on this call. */\n batch?: boolean | undefined\n /** Bytecode to perform the call on. */\n code?: Hex | undefined\n /** Contract deployment factory address (ie. Create2 factory, Smart Account factory, etc). */\n factory?: Address | undefined\n /** Calldata to execute on the factory to deploy the contract. */\n factoryData?: Hex | undefined\n /** State overrides for the call. */\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedCall =\n FormattedTransactionRequest\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | ScheduleMulticallErrorType\n | RequestErrorType\n | ToDeploylessCallViaBytecodeDataErrorType\n | ToDeploylessCallViaFactoryDataErrorType\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\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 blobs,\n code,\n data: data_,\n factory,\n factoryData,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n stateOverride,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n if (code && (factory || factoryData))\n throw new BaseError(\n 'Cannot provide both `code` & `factory`/`factoryData` as parameters.',\n )\n if (code && to)\n throw new BaseError('Cannot provide both `code` & `to` as parameters.')\n\n // Check if the call is deployless via bytecode.\n const deploylessCallViaBytecode = code && data_\n // Check if the call is deployless via a factory.\n const deploylessCallViaFactory = factory && factoryData && to && data_\n const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory\n\n const data = (() => {\n if (deploylessCallViaBytecode)\n return toDeploylessCallViaBytecodeData({\n code,\n data: data_,\n })\n if (deploylessCallViaFactory)\n return toDeploylessCallViaFactoryData({\n data: data_,\n factory,\n factoryData,\n to,\n })\n return data_\n })()\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\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 blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to: deploylessCall ? undefined : to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) {\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: rpcStateOverride\n ? [\n request as ExactPartial,\n block,\n rpcStateOverride,\n ]\n : [request as ExactPartial, block],\n })\n if (response === '0x') return { data: undefined }\n return { data: response }\n } catch (err) {\n const data = getRevertErrorData(err)\n\n // Check for CCIP-Read offchain lookup signature.\n const { offchainLookup, offchainLookupSignature } = await import(\n '../../utils/ccip.js'\n )\n if (\n client.ccipRead !== false &&\n data?.slice(0, 10) === offchainLookupSignature &&\n to\n )\n return { data: await offchainLookup(client, { data, to }) }\n\n // Check for counterfactual deployment error.\n if (deploylessCall && data?.slice(0, 10) === '0x101bb98d')\n throw new CounterfactualDeploymentFailedError({ factory })\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 | undefined\n to: Address\n}\n\ntype 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\ntype ToDeploylessCallViaBytecodeDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaBytecodeData(parameters: {\n code: Hex\n data: Hex\n}) {\n const { code, data } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(bytes, bytes)']),\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [code, data],\n })\n}\n\ntype ToDeploylessCallViaFactoryDataErrorType =\n | EncodeDeployDataErrorType\n | ErrorType\n\nfunction toDeploylessCallViaFactoryData(parameters: {\n data: Hex\n factory: Address\n factoryData: Hex\n to: Address\n}) {\n const { data, factory, factoryData, to } = parameters\n return encodeDeployData({\n abi: parseAbi(['constructor(address, bytes, address, bytes)']),\n bytecode: deploylessCallViaFactoryBytecode,\n args: [to, data, factory, factoryData],\n })\n}\n\n/** @internal */\nexport type GetRevertErrorDataErrorType = ErrorType\n\n/** @internal */\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 { Address } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type OffchainLookupErrorType = OffchainLookupError & {\n name: 'OffchainLookupError'\n}\nexport class OffchainLookupError extends BaseError {\n constructor({\n callbackSelector,\n cause,\n data,\n extraData,\n sender,\n urls,\n }: {\n callbackSelector: Hex\n cause: BaseError\n data: Hex\n extraData: Hex\n sender: Address\n urls: readonly string[]\n }) {\n super(\n cause.shortMessage ||\n 'An error occurred while fetching for an offchain result.',\n {\n cause,\n metaMessages: [\n ...(cause.metaMessages || []),\n cause.metaMessages?.length ? '' : [],\n 'Offchain Gateway Call:',\n urls && [\n ' Gateway URL(s):',\n ...urls.map((url) => ` ${getUrl(url)}`),\n ],\n ` Sender: ${sender}`,\n ` Data: ${data}`,\n ` Callback selector: ${callbackSelector}`,\n ` Extra data: ${extraData}`,\n ].flat(),\n name: 'OffchainLookupError',\n },\n )\n }\n}\n\nexport type OffchainLookupResponseMalformedErrorType =\n OffchainLookupResponseMalformedError & {\n name: 'OffchainLookupResponseMalformedError'\n }\nexport class OffchainLookupResponseMalformedError extends BaseError {\n constructor({ result, url }: { result: any; url: string }) {\n super(\n 'Offchain gateway response is malformed. Response data must be a hex value.',\n {\n metaMessages: [\n `Gateway URL: ${getUrl(url)}`,\n `Response: ${stringify(result)}`,\n ],\n name: 'OffchainLookupResponseMalformedError',\n },\n )\n }\n}\n\n/** @internal */\nexport type OffchainLookupSenderMismatchErrorType =\n OffchainLookupSenderMismatchError & {\n name: 'OffchainLookupSenderMismatchError'\n }\nexport class OffchainLookupSenderMismatchError extends BaseError {\n constructor({ sender, to }: { sender: Address; to: Address }) {\n super(\n 'Reverted sender address does not match target contract address (`to`).',\n {\n metaMessages: [\n `Contract address: ${to}`,\n `OffchainLookup sender address: ${sender}`,\n ],\n name: 'OffchainLookupSenderMismatchError',\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { isAddress } from './isAddress.js'\n\nexport type IsAddressEqualReturnType = boolean\nexport type IsAddressEqualErrorType = InvalidAddressErrorType | ErrorType\n\nexport function isAddressEqual(a: Address, b: Address) {\n if (!isAddress(a, { strict: false }))\n throw new InvalidAddressError({ address: a })\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b })\n return a.toLowerCase() === b.toLowerCase()\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { BaseError } from '../errors/base.js'\nimport {\n OffchainLookupError,\n type OffchainLookupErrorType as OffchainLookupErrorType_,\n OffchainLookupResponseMalformedError,\n type OffchainLookupResponseMalformedErrorType,\n OffchainLookupSenderMismatchError,\n} from '../errors/ccip.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n} from '../errors/request.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\n\nimport type { Client } from '../clients/createClient.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport { decodeErrorResult } from './abi/decodeErrorResult.js'\nimport { encodeAbiParameters } from './abi/encodeAbiParameters.js'\nimport { isAddressEqual } from './address/isAddressEqual.js'\nimport { concat } from './data/concat.js'\nimport { isHex } from './data/isHex.js'\nimport { stringify } from './stringify.js'\n\nexport const offchainLookupSignature = '0x556f1830'\nexport const offchainLookupAbiItem = {\n name: 'OffchainLookup',\n type: 'error',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'urls',\n type: 'string[]',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n {\n name: 'callbackFunction',\n type: 'bytes4',\n },\n {\n name: 'extraData',\n type: 'bytes',\n },\n ],\n} as const satisfies Abi[number]\n\nexport type OffchainLookupErrorType = OffchainLookupErrorType_ | ErrorType\n\nexport async function offchainLookup(\n client: Client,\n {\n blockNumber,\n blockTag,\n data,\n to,\n }: Pick & {\n data: Hex\n to: Address\n },\n): Promise {\n const { args } = decodeErrorResult({\n data,\n abi: [offchainLookupAbiItem],\n })\n const [sender, urls, callData, callbackSelector, extraData] = args\n\n const { ccipRead } = client\n const ccipRequest_ =\n ccipRead && typeof ccipRead?.request === 'function'\n ? ccipRead.request\n : ccipRequest\n\n try {\n if (!isAddressEqual(to, sender))\n throw new OffchainLookupSenderMismatchError({ sender, to })\n\n const result = await ccipRequest_({ data: callData, sender, urls })\n\n const { data: data_ } = await call(client, {\n blockNumber,\n blockTag,\n data: concat([\n callbackSelector,\n encodeAbiParameters(\n [{ type: 'bytes' }, { type: 'bytes' }],\n [result, extraData],\n ),\n ]),\n to,\n } as CallParameters)\n\n return data_!\n } catch (err) {\n throw new OffchainLookupError({\n callbackSelector,\n cause: err as BaseError,\n data,\n extraData,\n sender,\n urls,\n })\n }\n}\n\nexport type CcipRequestParameters = {\n data: Hex\n sender: Address\n urls: readonly string[]\n}\n\nexport type CcipRequestReturnType = Hex\n\nexport type CcipRequestErrorType =\n | HttpRequestErrorType\n | OffchainLookupResponseMalformedErrorType\n | ErrorType\n\nexport async function ccipRequest({\n data,\n sender,\n urls,\n}: CcipRequestParameters): Promise {\n let error = new Error('An unknown error occurred.')\n\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i]\n const method = url.includes('{data}') ? 'GET' : 'POST'\n const body = method === 'POST' ? { data, sender } : undefined\n const headers: HeadersInit =\n method === 'POST' ? { 'Content-Type': 'application/json' } : {}\n\n try {\n const response = await fetch(\n url.replace('{sender}', sender).replace('{data}', data),\n {\n body: JSON.stringify(body),\n headers,\n method,\n },\n )\n\n let result: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n ) {\n result = (await response.json()).data\n } else {\n result = (await response.text()) as any\n }\n\n if (!response.ok) {\n error = new HttpRequestError({\n body,\n details: result?.error\n ? stringify(result.error)\n : response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n continue\n }\n\n if (!isHex(result)) {\n error = new OffchainLookupResponseMalformedError({\n result,\n url,\n })\n continue\n }\n\n return result\n } catch (err) {\n error = new HttpRequestError({\n body,\n details: (err as Error).message,\n url,\n })\n }\n }\n\n throw error\n}\n"],"mappings":";AAAO,IAAM,UAAU;;;ACUjB,IAAO,YAAP,MAAO,mBAAkB,MAAK;EAQlC,YAAY,cAAsB,OAAsB,CAAA,GAAE;AACxD,UAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,UAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AACX,UAAM,UAAU;MACd,gBAAgB;MAChB;MACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;MACrD,GAAIA,YAAW,CAAC,4BAA4BA,SAAQ,EAAE,IAAI,CAAA;MAC1D,GAAI,UAAU,CAAC,YAAY,OAAO,EAAE,IAAI,CAAA;MACxC,oBAAoB,OAAO;MAC3B,KAAK,IAAI;AAEX,UAAM,OAAO;AA3Bf,WAAA,eAAA,MAAA,WAAA;;;;;;AACA,WAAA,eAAA,MAAA,YAAA;;;;;;AACA,WAAA,eAAA,MAAA,gBAAA;;;;;;AACA,WAAA,eAAA,MAAA,gBAAA;;;;;;AAES,WAAA,eAAA,MAAA,QAAA;;;;aAAO;;AAwBd,QAAI,KAAK;AAAO,WAAK,QAAQ,KAAK;AAClC,SAAK,UAAU;AACf,SAAK,WAAWA;AAChB,SAAK,eAAe,KAAK;AACzB,SAAK,eAAe;EACtB;;;;AC3CI,SAAU,UAAgB,OAAe,QAAc;AAC3D,QAAM,QAAQ,MAAM,KAAK,MAAM;AAC/B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,QAAQ,SAAS,CAAC;OAEtB;MACD;KACiB;AAEnB,WAAO;EACT,SAAS,KAAK;AACZ,UAAM,IAAI,oBAAoB;MAC5B;MACA,OAAO;MACP;MACA;MACA;MACA;KACD;EACH;AACF;AAeA,eAAsB,YAAY,EAChC,MACA,QACA,KAAI,GACkB;AACtB,MAAI,QAAQ,IAAI,MAAM,4BAA4B;AAElD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAClB,UAAM,SAAS,IAAI,SAAS,QAAQ,IAAI,QAAQ;AAChD,UAAM,OAAO,WAAW,SAAS,EAAE,MAAM,OAAM,IAAK;AACpD,UAAM,UACJ,WAAW,SAAS,EAAE,gBAAgB,mBAAkB,IAAK,CAAA;AAE/D,QAAI;AACF,YAAM,WAAW,MAAM,MACrB,IAAI,QAAQ,YAAY,MAAM,EAAE,QAAQ,UAAU,IAAI,GACtD;QACE,MAAM,KAAK,UAAU,IAAI;QACzB;QACA;OACD;AAGH,UAAI;AACJ,UACE,SAAS,QAAQ,IAAI,cAAc,GAAG,WAAW,kBAAkB,GACnE;AACA,kBAAU,MAAM,SAAS,KAAI,GAAI;MACnC,OAAO;AACL,iBAAU,MAAM,SAAS,KAAI;MAC/B;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,gBAAQ,IAAI,iBAAiB;UAC3B;UACA,SAAS,QAAQ,QACb,UAAU,OAAO,KAAK,IACtB,SAAS;UACb,SAAS,SAAS;UAClB,QAAQ,SAAS;UACjB;SACD;AACD;MACF;AAEA,UAAI,CAAC,MAAM,MAAM,GAAG;AAClB,gBAAQ,IAAI,qCAAqC;UAC/C;UACA;SACD;AACD;MACF;AAEA,aAAO;IACT,SAAS,KAAK;AACZ,cAAQ,IAAI,iBAAiB;QAC3B;QACA,SAAU,IAAc;QACxB;OACD;IACH;EACF;AAEA,QAAM;AACR;","names":["docsPath","version","docsPath","version","BaseError","docsPath","version","BaseError","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","BaseError","docsPath","BaseError","docsPath","BaseError","formatAbiItem","BaseError","docsPath","BaseError","size","size","BaseError","size","BaseError","size","size","size","encoder","BaseError","toBytes","toBytes","toBytes","toBytes","BaseError","BaseError","size","hash","BaseError","size","bytesRegex","integerRegex","size","integerRegex","length","BaseError","data","length","consumed","value","size","formatAbiItem","value","BaseError","BaseError","BaseError","BaseError","docsPath","BaseError","docsPath","docsPath","formatAbiItem","BaseError","BaseError","BaseError","docsPath","cause","formatted","args","split","BaseError","data","offchainLookup","offchainLookupSignature","args","size","BaseError"]} \ No newline at end of file diff --git a/dist/chunk-PR4QN5HX.js b/dist/chunk-PR4QN5HX.js deleted file mode 100644 index e9ed04f..0000000 --- a/dist/chunk-PR4QN5HX.js +++ /dev/null @@ -1,43 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] -}) : x)(function(x) { - if (typeof require !== "undefined") return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); -}); -var __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -export { - __require, - __commonJS, - __export, - __toESM -}; -//# sourceMappingURL=chunk-PR4QN5HX.js.map \ No newline at end of file diff --git a/dist/chunk-PR4QN5HX.js.map b/dist/chunk-PR4QN5HX.js.map deleted file mode 100644 index 84c51b2..0000000 --- a/dist/chunk-PR4QN5HX.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts deleted file mode 100644 index cdb3835..0000000 --- a/dist/index.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Plugin } from '@elizaos/core'; -import { Keypair } from '@solana/web3.js'; -import { DeriveKeyResponse, TdxQuoteHashAlgorithms } from '@phala/dstack-sdk'; -import { PrivateKeyAccount } from 'viem'; - -declare enum TEEMode { - OFF = "OFF", - LOCAL = "LOCAL",// For local development with simulator - DOCKER = "DOCKER",// For docker development with simulator - PRODUCTION = "PRODUCTION" -} -interface RemoteAttestationQuote { - quote: string; - timestamp: number; -} - -declare class DeriveKeyProvider { - private client; - private raProvider; - constructor(teeMode?: string); - private generateDeriveKeyAttestation; - /** - * Derives a raw key from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @returns The derived key. - */ - rawDeriveKey(path: string, subject: string): Promise; - /** - * Derives an Ed25519 keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. - * @returns An object containing the derived keypair and attestation. - */ - deriveEd25519Keypair(path: string, subject: string, agentId: string): Promise<{ - keypair: Keypair; - attestation: RemoteAttestationQuote; - }>; - /** - * Derives an ECDSA keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. - * @returns An object containing the derived keypair and attestation. - */ - deriveEcdsaKeypair(path: string, subject: string, agentId: string): Promise<{ - keypair: PrivateKeyAccount; - attestation: RemoteAttestationQuote; - }>; -} - -declare class RemoteAttestationProvider { - private client; - constructor(teeMode?: string); - generateAttestation(reportData: string, hashAlgorithm?: TdxQuoteHashAlgorithms): Promise; -} - -declare const teePlugin: Plugin; - -export { DeriveKeyProvider, RemoteAttestationProvider, type RemoteAttestationQuote, TEEMode, teePlugin }; diff --git a/dist/index.js b/dist/index.js index 39dafe0..257dbbb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,111 +1,65 @@ +// src/index.ts import { - secp256k1 -} from "./chunk-4L6P6TY5.js"; -import { - BaseError, - BytesSizeMismatchError, - FeeCapTooHighError, - Hash, - InvalidAddressError, - InvalidChainIdError, - InvalidLegacyVError, - InvalidSerializableTransactionError, - InvalidStorageKeySizeError, - TipAboveFeeCapError, - aexists, - aoutput, - bytesRegex, - bytesToHex, - checksumAddress, - concat, - concatHex, - createCursor, - createView, - encodeAbiParameters, - hexToBigInt, - hexToBytes, - hexToNumber, - integerRegex, - isAddress, - isHex, - keccak256, - maxUint256, - numberToHex, - rotr, - size, - slice, - stringToHex, - stringify, - toBytes, - toBytes2, - toHex, - trim, - wrapConstructor -} from "./chunk-NTU6R7BC.js"; -import "./chunk-PR4QN5HX.js"; + logger as logger4 +} from "@elizaos/core"; + +// src/vendors/types.ts +var TeeVendorNames = { + PHALA: "phala" +}; + +// src/actions/remoteAttestationAction.ts +import { logger as logger2 } from "@elizaos/core"; // src/providers/remoteAttestationProvider.ts -import { - elizaLogger -} from "@elizaos/core"; +import { logger } from "@elizaos/core"; +import { TEEMode } from "@elizaos/core"; import { TappdClient } from "@phala/dstack-sdk"; -// src/types/tee.ts -var TEEMode = /* @__PURE__ */ ((TEEMode2) => { - TEEMode2["OFF"] = "OFF"; - TEEMode2["LOCAL"] = "LOCAL"; - TEEMode2["DOCKER"] = "DOCKER"; - TEEMode2["PRODUCTION"] = "PRODUCTION"; - return TEEMode2; -})(TEEMode || {}); +// src/providers/base.ts +var DeriveKeyProvider = class { +}; +var RemoteAttestationProvider = class { +}; // src/providers/remoteAttestationProvider.ts -var RemoteAttestationProvider = class { +var PhalaRemoteAttestationProvider = class extends RemoteAttestationProvider { client; constructor(teeMode) { + super(); let endpoint; switch (teeMode) { - case "LOCAL" /* LOCAL */: + case TEEMode.LOCAL: endpoint = "http://localhost:8090"; - elizaLogger.log( - "TEE: Connecting to local simulator at localhost:8090" - ); + logger.log("TEE: Connecting to local simulator at localhost:8090"); break; - case "DOCKER" /* DOCKER */: + case TEEMode.DOCKER: endpoint = "http://host.docker.internal:8090"; - elizaLogger.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); + logger.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090"); break; - case "PRODUCTION" /* PRODUCTION */: + case TEEMode.PRODUCTION: endpoint = void 0; - elizaLogger.log( - "TEE: Running in production mode without simulator" - ); + logger.log("TEE: Running in production mode without simulator"); break; default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); + throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); } this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); } async generateAttestation(reportData, hashAlgorithm) { try { - elizaLogger.log("Generating attestation for: ", reportData); + logger.log("Generating attestation for: ", reportData); const tdxQuote = await this.client.tdxQuote(reportData, hashAlgorithm); const rtmrs = tdxQuote.replayRtmrs(); - elizaLogger.log( - `rtmr0: ${rtmrs[0]} + logger.log(`rtmr0: ${rtmrs[0]} rtmr1: ${rtmrs[1]} rtmr2: ${rtmrs[2]} -rtmr3: ${rtmrs[3]}f` - ); +rtmr3: ${rtmrs[3]}f`); const quote = { quote: tdxQuote.quote, timestamp: Date.now() }; - elizaLogger.log("Remote attestation quote: ", quote); + logger.log("Remote attestation quote: ", quote); return quote; } catch (error) { console.error("Error generating remote attestation:", error); @@ -115,24 +69,34 @@ rtmr3: ${rtmrs[3]}f` } } }; -var remoteAttestationProvider = { - get: async (runtime, message, _state) => { +var phalaRemoteAttestationProvider = { + name: "phala-remote-attestation", + get: async (runtime, message) => { const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new RemoteAttestationProvider(teeMode); + const provider = new PhalaRemoteAttestationProvider(teeMode); const agentId = runtime.agentId; try { const attestationMessage = { agentId, timestamp: Date.now(), message: { - userId: message.userId, + entityId: message.entityId, roomId: message.roomId, content: message.content.text } }; - elizaLogger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); + logger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); - return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; + return { + text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`, + data: { + attestation + }, + values: { + quote: attestation.quote, + timestamp: attestation.timestamp.toString() + } + }; } catch (error) { console.error("Error in remote attestation provider:", error); throw new Error( @@ -142,1251 +106,159 @@ var remoteAttestationProvider = { } }; -// src/providers/deriveKeyProvider.ts -import { - elizaLogger as elizaLogger2 -} from "@elizaos/core"; -import { Keypair } from "@solana/web3.js"; -import crypto from "crypto"; -import { TappdClient as TappdClient2 } from "@phala/dstack-sdk"; - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/_md.js -function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); -} -var Chi = (a, b, c) => a & b ^ ~a & c; -var Maj = (a, b, c) => a & b ^ a & c ^ b & c; -var HashMD = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - aexists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } -}; - -// ../../node_modules/viem/node_modules/@noble/hashes/esm/sha256.js -var SHA256_K = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -var SHA256_IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA256_W = /* @__PURE__ */ new Uint32Array(64); -var SHA256 = class extends HashMD { - constructor() { - super(64, 32, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; +// src/utils.ts +function hexToUint8Array(hex) { + const hexString = hex.trim().replace(/^0x/, ""); + if (!hexString) { + throw new Error("Invalid hex string"); } - // prettier-ignore - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; + if (hexString.length % 2 !== 0) { + throw new Error("Invalid hex string"); } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; + const array = new Uint8Array(hexString.length / 2); + for (let i = 0; i < hexString.length; i += 2) { + const byte = Number.parseInt(hexString.slice(i, i + 2), 16); + if (Number.isNaN(byte)) { + throw new Error("Invalid hex string"); } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } -}; -var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); - -// ../../node_modules/viem/_esm/accounts/toAccount.js -function toAccount(source) { - if (typeof source === "string") { - if (!isAddress(source, { strict: false })) - throw new InvalidAddressError({ address: source }); - return { - address: source, - type: "json-rpc" - }; + array[i / 2] = byte; } - if (!isAddress(source.address, { strict: false })) - throw new InvalidAddressError({ address: source.address }); - return { - address: source.address, - nonceManager: source.nonceManager, - sign: source.sign, - experimental_signAuthorization: source.experimental_signAuthorization, - signMessage: source.signMessage, - signTransaction: source.signTransaction, - signTypedData: source.signTypedData, - source: "custom", - type: "local" - }; -} - -// ../../node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js -function publicKeyToAddress(publicKey) { - const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); - return checksumAddress(`0x${address}`); -} - -// ../../node_modules/viem/_esm/utils/signature/serializeSignature.js -function serializeSignature({ r, s, to = "hex", 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"); - })(); - const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; - if (to === "hex") - return signature; - return hexToBytes(signature); -} - -// ../../node_modules/viem/_esm/accounts/utils/sign.js -var extraEntropy = false; -async function sign({ hash, privateKey, to = "object" }) { - const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), { lowS: true, extraEntropy }); - const signature = { - r: numberToHex(r, { size: 32 }), - s: numberToHex(s, { size: 32 }), - v: recovery ? 28n : 27n, - yParity: recovery - }; - return (() => { - if (to === "bytes" || to === "hex") - return serializeSignature({ ...signature, to }); - return signature; - })(); -} - -// ../../node_modules/viem/_esm/utils/encoding/toRlp.js -function toRlp(bytes, to = "hex") { - const encodable = getEncodable(bytes); - const cursor = createCursor(new Uint8Array(encodable.length)); - encodable.encode(cursor); - if (to === "hex") - return bytesToHex(cursor.bytes); - return cursor.bytes; -} -function getEncodable(bytes) { - if (Array.isArray(bytes)) - return getEncodableList(bytes.map((x) => getEncodable(x))); - return getEncodableBytes(bytes); -} -function getEncodableList(list) { - const bodyLength = list.reduce((acc, x) => acc + x.length, 0); - const sizeOfBodyLength = getSizeOfLength(bodyLength); - const length = (() => { - if (bodyLength <= 55) - return 1 + bodyLength; - return 1 + sizeOfBodyLength + bodyLength; - })(); - return { - length, - encode(cursor) { - if (bodyLength <= 55) { - cursor.pushByte(192 + bodyLength); - } else { - cursor.pushByte(192 + 55 + sizeOfBodyLength); - if (sizeOfBodyLength === 1) - cursor.pushUint8(bodyLength); - else if (sizeOfBodyLength === 2) - cursor.pushUint16(bodyLength); - else if (sizeOfBodyLength === 3) - cursor.pushUint24(bodyLength); - else - cursor.pushUint32(bodyLength); - } - for (const { encode } of list) { - encode(cursor); - } - } - }; -} -function getEncodableBytes(bytesOrHex) { - const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; - const sizeOfBytesLength = getSizeOfLength(bytes.length); - const length = (() => { - if (bytes.length === 1 && bytes[0] < 128) - return 1; - if (bytes.length <= 55) - return 1 + bytes.length; - return 1 + sizeOfBytesLength + bytes.length; - })(); - return { - length, - encode(cursor) { - if (bytes.length === 1 && bytes[0] < 128) { - cursor.pushBytes(bytes); - } else if (bytes.length <= 55) { - cursor.pushByte(128 + bytes.length); - cursor.pushBytes(bytes); - } else { - cursor.pushByte(128 + 55 + sizeOfBytesLength); - if (sizeOfBytesLength === 1) - cursor.pushUint8(bytes.length); - else if (sizeOfBytesLength === 2) - cursor.pushUint16(bytes.length); - else if (sizeOfBytesLength === 3) - cursor.pushUint24(bytes.length); - else - cursor.pushUint32(bytes.length); - cursor.pushBytes(bytes); - } - } - }; -} -function getSizeOfLength(length) { - if (length < 2 ** 8) - return 1; - if (length < 2 ** 16) - return 2; - if (length < 2 ** 24) - return 3; - if (length < 2 ** 32) - return 4; - throw new BaseError("Length is too large."); -} - -// ../../node_modules/viem/_esm/experimental/eip7702/utils/hashAuthorization.js -function hashAuthorization(parameters) { - const { chainId, contractAddress, nonce, to } = parameters; - const hash = keccak256(concatHex([ - "0x05", - toRlp([ - chainId ? numberToHex(chainId) : "0x", - contractAddress, - nonce ? numberToHex(nonce) : "0x" - ]) - ])); - if (to === "bytes") - return hexToBytes(hash); - return hash; + return array; } -// ../../node_modules/viem/_esm/accounts/utils/signAuthorization.js -async function experimental_signAuthorization(parameters) { - const { contractAddress, chainId, nonce, privateKey, to = "object" } = parameters; - const signature = await sign({ - hash: hashAuthorization({ contractAddress, chainId, nonce }), - privateKey, - to +// src/actions/remoteAttestationAction.ts +async function uploadUint8Array(data) { + const blob = new Blob([data], { type: "application/octet-stream" }); + const formData = new FormData(); + formData.append("file", blob, "quote.bin"); + return await fetch("https://proof.t16z.com/api/upload", { + method: "POST", + body: formData }); - if (to === "object") - return { - contractAddress, - chainId, - nonce, - ...signature - }; - return signature; -} - -// ../../node_modules/viem/_esm/constants/strings.js -var presignMessagePrefix = "Ethereum Signed Message:\n"; - -// ../../node_modules/viem/_esm/utils/signature/toPrefixedMessage.js -function toPrefixedMessage(message_) { - const message = (() => { - if (typeof message_ === "string") - return stringToHex(message_); - if (typeof message_.raw === "string") - return message_.raw; - return bytesToHex(message_.raw); - })(); - const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); - return concat([prefix, message]); } - -// ../../node_modules/viem/_esm/utils/signature/hashMessage.js -function hashMessage(message, to_) { - return keccak256(toPrefixedMessage(message), to_); -} - -// ../../node_modules/viem/_esm/accounts/utils/signMessage.js -async function signMessage({ message, privateKey }) { - return await sign({ hash: hashMessage(message), privateKey, to: "hex" }); -} - -// ../../node_modules/viem/_esm/utils/blob/blobsToCommitments.js -function blobsToCommitments(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; - const commitments = []; - for (const blob of blobs) - commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); - return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x)); -} - -// ../../node_modules/viem/_esm/utils/blob/blobsToProofs.js -function blobsToProofs(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; - const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments; - const proofs = []; - for (let i = 0; i < blobs.length; i++) { - const blob = blobs[i]; - const commitment = commitments[i]; - proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); - } - return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x)); -} - -// ../../node_modules/viem/_esm/utils/hash/sha256.js -function sha2562(value, to_) { - const to = to_ || "hex"; - const bytes = sha256(isHex(value, { strict: false }) ? toBytes2(value) : value); - if (to === "bytes") - return bytes; - return toHex(bytes); -} - -// ../../node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js -function commitmentToVersionedHash(parameters) { - const { commitment, version = 1 } = parameters; - const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); - const versionedHash = sha2562(commitment, "bytes"); - versionedHash.set([version], 0); - return to === "bytes" ? versionedHash : bytesToHex(versionedHash); -} - -// ../../node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js -function commitmentsToVersionedHashes(parameters) { - const { commitments, version } = parameters; - const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); - const hashes = []; - for (const commitment of commitments) { - hashes.push(commitmentToVersionedHash({ - commitment, - to, - version - })); - } - return hashes; -} - -// ../../node_modules/viem/_esm/constants/blob.js -var blobsPerTransaction = 6; -var bytesPerFieldElement = 32; -var fieldElementsPerBlob = 4096; -var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; -var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). -1 - // zero byte (0x00) appended to each field element. -1 * fieldElementsPerBlob * blobsPerTransaction; - -// ../../node_modules/viem/_esm/constants/kzg.js -var versionedHashVersionKzg = 1; - -// ../../node_modules/viem/_esm/errors/blob.js -var BlobSizeTooLargeError = class extends BaseError { - constructor({ maxSize, size: size2 }) { - super("Blob size is too large.", { - metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`], - name: "BlobSizeTooLargeError" - }); - } -}; -var EmptyBlobError = class extends BaseError { - constructor() { - super("Blob data must not be empty.", { name: "EmptyBlobError" }); - } -}; -var InvalidVersionedHashSizeError = class extends BaseError { - constructor({ hash, size: size2 }) { - super(`Versioned hash "${hash}" size is invalid.`, { - metaMessages: ["Expected: 32", `Received: ${size2}`], - name: "InvalidVersionedHashSizeError" - }); - } -}; -var InvalidVersionedHashVersionError = class extends BaseError { - constructor({ hash, version }) { - super(`Versioned hash "${hash}" version is invalid.`, { - metaMessages: [ - `Expected: ${versionedHashVersionKzg}`, - `Received: ${version}` - ], - name: "InvalidVersionedHashVersionError" - }); - } -}; - -// ../../node_modules/viem/_esm/utils/blob/toBlobs.js -function toBlobs(parameters) { - const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); - const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; - const size_ = size(data); - if (!size_) - throw new EmptyBlobError(); - if (size_ > maxBytesPerTransaction) - throw new BlobSizeTooLargeError({ - maxSize: maxBytesPerTransaction, - size: size_ - }); - const blobs = []; - let active = true; - let position = 0; - while (active) { - const blob = createCursor(new Uint8Array(bytesPerBlob)); - let size2 = 0; - while (size2 < fieldElementsPerBlob) { - const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); - blob.pushByte(0); - blob.pushBytes(bytes); - if (bytes.length < 31) { - blob.pushByte(128); - active = false; - break; - } - size2++; - position += 31; - } - blobs.push(blob); - } - return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes)); -} - -// ../../node_modules/viem/_esm/utils/blob/toBlobSidecars.js -function toBlobSidecars(parameters) { - const { data, kzg, to } = parameters; - const blobs = parameters.blobs ?? toBlobs({ data, to }); - const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); - const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); - const sidecars = []; - for (let i = 0; i < blobs.length; i++) - sidecars.push({ - blob: blobs[i], - commitment: commitments[i], - proof: proofs[i] - }); - return sidecars; -} - -// ../../node_modules/viem/_esm/experimental/eip7702/utils/serializeAuthorizationList.js -function serializeAuthorizationList(authorizationList) { - if (!authorizationList || authorizationList.length === 0) - return []; - const serializedAuthorizationList = []; - for (const authorization of authorizationList) { - const { contractAddress, chainId, nonce, ...signature } = authorization; - serializedAuthorizationList.push([ - chainId ? toHex(chainId) : "0x", - contractAddress, - nonce ? toHex(nonce) : "0x", - ...toYParitySignatureArray({}, signature) - ]); - } - return serializedAuthorizationList; -} - -// ../../node_modules/viem/_esm/utils/transaction/assertTransaction.js -function assertTransactionEIP7702(transaction) { - const { authorizationList } = transaction; - if (authorizationList) { - for (const authorization of authorizationList) { - const { contractAddress, chainId } = authorization; - if (!isAddress(contractAddress)) - throw new InvalidAddressError({ address: contractAddress }); - if (chainId < 0) - throw new InvalidChainIdError({ chainId }); - } - } - assertTransactionEIP1559(transaction); -} -function assertTransactionEIP4844(transaction) { - const { blobVersionedHashes } = transaction; - if (blobVersionedHashes) { - if (blobVersionedHashes.length === 0) - throw new EmptyBlobError(); - for (const hash of blobVersionedHashes) { - const size_ = size(hash); - const version = hexToNumber(slice(hash, 0, 1)); - if (size_ !== 32) - throw new InvalidVersionedHashSizeError({ hash, size: size_ }); - if (version !== versionedHashVersionKzg) - throw new InvalidVersionedHashVersionError({ - hash, - version - }); - } - } - assertTransactionEIP1559(transaction); -} -function assertTransactionEIP1559(transaction) { - const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); -} -function assertTransactionEIP2930(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); -} -function assertTransactionLegacy(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (typeof chainId !== "undefined" && chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); -} - -// ../../node_modules/viem/_esm/utils/transaction/getTransactionType.js -function getTransactionType(transaction) { - if (transaction.type) - return transaction.type; - if (typeof transaction.authorizationList !== "undefined") - return "eip7702"; - if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") - return "eip4844"; - if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { - return "eip1559"; - } - if (typeof transaction.gasPrice !== "undefined") { - if (typeof transaction.accessList !== "undefined") - return "eip2930"; - return "legacy"; - } - throw new InvalidSerializableTransactionError({ transaction }); -} - -// ../../node_modules/viem/_esm/utils/transaction/serializeAccessList.js -function serializeAccessList(accessList) { - if (!accessList || accessList.length === 0) - return []; - const serializedAccessList = []; - for (let i = 0; i < accessList.length; i++) { - const { address, storageKeys } = accessList[i]; - for (let j = 0; j < storageKeys.length; j++) { - if (storageKeys[j].length - 2 !== 64) { - throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] }); - } - } - if (!isAddress(address, { strict: false })) { - throw new InvalidAddressError({ address }); - } - serializedAccessList.push([address, storageKeys]); - } - return serializedAccessList; -} - -// ../../node_modules/viem/_esm/utils/transaction/serializeTransaction.js -function serializeTransaction(transaction, signature) { - const type = getTransactionType(transaction); - if (type === "eip1559") - return serializeTransactionEIP1559(transaction, signature); - if (type === "eip2930") - return serializeTransactionEIP2930(transaction, signature); - if (type === "eip4844") - return serializeTransactionEIP4844(transaction, signature); - if (type === "eip7702") - return serializeTransactionEIP7702(transaction, signature); - return serializeTransactionLegacy(transaction, signature); -} -function serializeTransactionEIP7702(transaction, signature) { - const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP7702(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedAuthorizationList = serializeAuthorizationList(authorizationList); - return concatHex([ - "0x04", - toRlp([ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - serializedAuthorizationList, - ...toYParitySignatureArray(transaction, signature) - ]) - ]); -} -function serializeTransactionEIP4844(transaction, signature) { - const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP4844(transaction); - let blobVersionedHashes = transaction.blobVersionedHashes; - let sidecars = transaction.sidecars; - if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { - const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x)); - const kzg = transaction.kzg; - const commitments2 = blobsToCommitments({ - blobs: blobs2, - kzg - }); - if (typeof blobVersionedHashes === "undefined") - blobVersionedHashes = commitmentsToVersionedHashes({ - commitments: commitments2 +var phalaRemoteAttestationAction = { + name: "REMOTE_ATTESTATION", + similes: [ + "REMOTE_ATTESTATION", + "TEE_REMOTE_ATTESTATION", + "TEE_ATTESTATION", + "TEE_QUOTE", + "ATTESTATION", + "TEE_ATTESTATION_QUOTE" + ], + description: "Generate a remote attestation to prove that the agent is running in a TEE", + handler: async (runtime, message, _state, _options, callback) => { + try { + const attestationMessage = { + agentId: runtime.agentId, + timestamp: Date.now(), + message: { + entityId: message.entityId, + roomId: message.roomId, + content: message.content.text + } + }; + const teeMode = runtime.getSetting("TEE_MODE"); + logger2.debug(`Tee mode: ${teeMode}`); + logger2.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`); + const provider = new PhalaRemoteAttestationProvider(teeMode); + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + const attestationData = hexToUint8Array(attestation.quote); + const response = await uploadUint8Array(attestationData); + const data = await response.json(); + callback({ + text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} +https://proof.t16z.com/reports/${data.checksum}`, + actions: ["NONE"] }); - if (typeof sidecars === "undefined") { - const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); - sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); - } - } - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x", - blobVersionedHashes ?? [], - ...toYParitySignatureArray(transaction, signature) - ]; - const blobs = []; - const commitments = []; - const proofs = []; - if (sidecars) - for (let i = 0; i < sidecars.length; i++) { - const { blob, commitment, proof } = sidecars[i]; - blobs.push(blob); - commitments.push(commitment); - proofs.push(proof); + return true; + } catch (error) { + console.error("Failed to fetch remote attestation: ", error); + return false; } - return concatHex([ - "0x03", - sidecars ? ( - // If sidecars are enabled, envelope turns into a "wrapper": - toRlp([serializedTransaction, blobs, commitments, proofs]) - ) : ( - // If sidecars are disabled, standard envelope is used: - toRlp(serializedTransaction) - ) - ]); -} -function serializeTransactionEIP1559(transaction, signature) { - const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP1559(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x02", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionEIP2930(transaction, signature) { - const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction; - assertTransactionEIP2930(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - gasPrice ? toHex(gasPrice) : "0x", - gas ? toHex(gas) : "0x", - to ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x01", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionLegacy(transaction, signature) { - const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction; - assertTransactionLegacy(transaction); - let serializedTransaction = [ - nonce ? toHex(nonce) : "0x", - gasPrice ? toHex(gasPrice) : "0x", - gas ? toHex(gas) : "0x", - to ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x" - ]; - if (signature) { - const v = (() => { - if (signature.v >= 35n) { - const inferredChainId = (signature.v - 35n) / 2n; - if (inferredChainId > 0) - return signature.v; - return 27n + (signature.v === 35n ? 0n : 1n); - } - if (chainId > 0) - return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); - const v2 = 27n + (signature.v === 27n ? 0n : 1n); - if (signature.v !== v2) - throw new InvalidLegacyVError({ v: signature.v }); - return v2; - })(); - const r = trim(signature.r); - const s = trim(signature.s); - serializedTransaction = [ - ...serializedTransaction, - toHex(v), - r === "0x00" ? "0x" : r, - s === "0x00" ? "0x" : s - ]; - } else if (chainId > 0) { - serializedTransaction = [ - ...serializedTransaction, - toHex(chainId), - "0x", - "0x" - ]; - } - return toRlp(serializedTransaction); -} -function toYParitySignatureArray(transaction, signature_) { - const signature = signature_ ?? transaction; - const { v, yParity } = signature; - if (typeof signature.r === "undefined") - return []; - if (typeof signature.s === "undefined") - return []; - if (typeof v === "undefined" && typeof yParity === "undefined") - return []; - const r = trim(signature.r); - const s = trim(signature.s); - const yParity_ = (() => { - if (typeof yParity === "number") - return yParity ? toHex(1) : "0x"; - if (v === 0n) - return "0x"; - if (v === 1n) - return toHex(1); - return v === 27n ? "0x" : toHex(1); - })(); - return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; -} - -// ../../node_modules/viem/_esm/accounts/utils/signTransaction.js -async function signTransaction(parameters) { - const { privateKey, transaction, serializer = serializeTransaction } = parameters; - const signableTransaction = (() => { - if (transaction.type === "eip4844") - return { - ...transaction, - sidecars: false - }; - return transaction; - })(); - const signature = await sign({ - hash: keccak256(serializer(signableTransaction)), - privateKey - }); - return serializer(transaction, signature); -} - -// ../../node_modules/viem/_esm/errors/typedData.js -var InvalidDomainError = class extends BaseError { - constructor({ domain }) { - super(`Invalid domain "${stringify(domain)}".`, { - metaMessages: ["Must be a valid EIP-712 domain."] - }); - } -}; -var InvalidPrimaryTypeError = class extends BaseError { - constructor({ primaryType, types }) { - super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { - docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", - metaMessages: ["Check that the primary type is a key in `types`."] - }); - } -}; -var InvalidStructTypeError = class extends BaseError { - constructor({ type }) { - super(`Struct type "${type}" is invalid.`, { - metaMessages: ["Struct type must not be a Solidity type."], - name: "InvalidStructTypeError" - }); - } -}; - -// ../../node_modules/viem/_esm/utils/typedData.js -function validateTypedData(parameters) { - const { domain, message, primaryType, types } = parameters; - const validateData = (struct, data) => { - for (const param of struct) { - const { name, type } = param; - const value = data[name]; - const integerMatch = type.match(integerRegex); - if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { - const [_type, base, size_] = integerMatch; - numberToHex(value, { - signed: base === "int", - size: Number.parseInt(size_) / 8 - }); + }, + validate: async (_runtime) => { + return true; + }, + examples: [ + [ + { + name: "{{name1}}", + content: { + text: "If you are running in a TEE, generate a remote attestation" + } + }, + { + name: "{{agentName}}", + content: { + text: "Of course, one second...", + actions: ["REMOTE_ATTESTATION"] + } } - if (type === "address" && typeof value === "string" && !isAddress(value)) - throw new InvalidAddressError({ address: value }); - const bytesMatch = type.match(bytesRegex); - if (bytesMatch) { - const [_type, size_] = bytesMatch; - if (size_ && size(value) !== Number.parseInt(size_)) - throw new BytesSizeMismatchError({ - expectedSize: Number.parseInt(size_), - givenSize: size(value) - }); + ], + [ + { + name: "{{name1}}", + content: { + text: "Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?" + } + }, + { + name: "{{agentName}}", + content: { + text: "I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!", + actions: ["REMOTE_ATTESTATION"] + } } - const struct2 = types[type]; - if (struct2) { - validateReference(type); - validateData(struct2, value); + ], + [ + { + name: "{{name1}}", + content: { + text: "It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'" + } + }, + { + name: "{{agentName}}", + content: { + text: "Oh, dear...lemme find that for you", + actions: ["REMOTE_ATTESTATION"] + } } - } - }; - if (types.EIP712Domain && domain) { - if (typeof domain !== "object") - throw new InvalidDomainError({ domain }); - validateData(types.EIP712Domain, domain); - } - if (primaryType !== "EIP712Domain") { - if (types[primaryType]) - validateData(types[primaryType], message); - else - throw new InvalidPrimaryTypeError({ primaryType, types }); - } -} -function getTypesForEIP712Domain({ domain }) { - return [ - typeof domain?.name === "string" && { name: "name", type: "string" }, - domain?.version && { name: "version", type: "string" }, - typeof domain?.chainId === "number" && { - name: "chainId", - type: "uint256" - }, - domain?.verifyingContract && { - name: "verifyingContract", - type: "address" - }, - domain?.salt && { name: "salt", type: "bytes32" } - ].filter(Boolean); -} -function validateReference(type) { - if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) - throw new InvalidStructTypeError({ type }); -} - -// ../../node_modules/viem/_esm/utils/signature/hashTypedData.js -function hashTypedData(parameters) { - const { domain = {}, message, primaryType } = parameters; - const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), - ...parameters.types - }; - validateTypedData({ - domain, - message, - primaryType, - types - }); - const parts = ["0x1901"]; - if (domain) - parts.push(hashDomain({ - domain, - types - })); - if (primaryType !== "EIP712Domain") - parts.push(hashStruct({ - data: message, - primaryType, - types - })); - return keccak256(concat(parts)); -} -function hashDomain({ domain, types }) { - return hashStruct({ - data: domain, - primaryType: "EIP712Domain", - types - }); -} -function hashStruct({ data, primaryType, types }) { - const encoded = encodeData({ - data, - primaryType, - types - }); - return keccak256(encoded); -} -function encodeData({ data, primaryType, types }) { - const encodedTypes = [{ type: "bytes32" }]; - const encodedValues = [hashType({ primaryType, types })]; - for (const field of types[primaryType]) { - const [type, value] = encodeField({ - types, - name: field.name, - type: field.type, - value: data[field.name] - }); - encodedTypes.push(type); - encodedValues.push(value); - } - return encodeAbiParameters(encodedTypes, encodedValues); -} -function hashType({ primaryType, types }) { - const encodedHashType = toHex(encodeType({ primaryType, types })); - return keccak256(encodedHashType); -} -function encodeType({ primaryType, types }) { - let result = ""; - const unsortedDeps = findTypeDependencies({ primaryType, types }); - unsortedDeps.delete(primaryType); - const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; - for (const type of deps) { - result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; - } - return result; -} -function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) { - const match = primaryType_.match(/^\w*/u); - const primaryType = match?.[0]; - if (results.has(primaryType) || types[primaryType] === void 0) { - return results; - } - results.add(primaryType); - for (const field of types[primaryType]) { - findTypeDependencies({ primaryType: field.type, types }, results); - } - return results; -} -function encodeField({ types, name, type, value }) { - if (types[type] !== void 0) { - return [ - { type: "bytes32" }, - keccak256(encodeData({ data: value, primaryType: type, types })) - ]; - } - if (type === "bytes") { - const prepend = value.length % 2 ? "0" : ""; - value = `0x${prepend + value.slice(2)}`; - return [{ type: "bytes32" }, keccak256(value)]; - } - if (type === "string") - return [{ type: "bytes32" }, keccak256(toHex(value))]; - if (type.lastIndexOf("]") === type.length - 1) { - const parsedType = type.slice(0, type.lastIndexOf("[")); - const typeValuePairs = value.map((item) => encodeField({ - name, - type: parsedType, - types, - value: item - })); - return [ - { type: "bytes32" }, - keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) - ]; - } - return [{ type }, value]; -} - -// ../../node_modules/viem/_esm/accounts/utils/signTypedData.js -async function signTypedData(parameters) { - const { privateKey, ...typedData } = parameters; - return await sign({ - hash: hashTypedData(typedData), - privateKey, - to: "hex" - }); -} - -// ../../node_modules/viem/_esm/accounts/privateKeyToAccount.js -function privateKeyToAccount(privateKey, options = {}) { - const { nonceManager } = options; - const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false)); - const address = publicKeyToAddress(publicKey); - const account = toAccount({ - address, - nonceManager, - async sign({ hash }) { - return sign({ hash, privateKey, to: "hex" }); - }, - async experimental_signAuthorization(authorization) { - return experimental_signAuthorization({ ...authorization, privateKey }); - }, - async signMessage({ message }) { - return signMessage({ message, privateKey }); - }, - async signTransaction(transaction, { serializer } = {}) { - return signTransaction({ privateKey, transaction, serializer }); - }, - async signTypedData(typedData) { - return signTypedData({ ...typedData, privateKey }); - } - }); - return { - ...account, - publicKey, - source: "privateKey" - }; -} + ] + ] +}; // src/providers/deriveKeyProvider.ts -var DeriveKeyProvider = class { +import { logger as logger3 } from "@elizaos/core"; +import { TEEMode as TEEMode2 } from "@elizaos/core"; +import { TappdClient as TappdClient2 } from "@phala/dstack-sdk"; +import { toViemAccount } from "@phala/dstack-sdk/viem"; +import { toKeypair } from "@phala/dstack-sdk/solana"; +var PhalaDeriveKeyProvider = class extends DeriveKeyProvider { client; raProvider; constructor(teeMode) { + super(); let endpoint; switch (teeMode) { - case "LOCAL" /* LOCAL */: + case TEEMode2.LOCAL: endpoint = "http://localhost:8090"; - elizaLogger2.log( - "TEE: Connecting to local simulator at localhost:8090" - ); + logger3.log("TEE: Connecting to local simulator at localhost:8090"); break; - case "DOCKER" /* DOCKER */: + case TEEMode2.DOCKER: endpoint = "http://host.docker.internal:8090"; - elizaLogger2.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); + logger3.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090"); break; - case "PRODUCTION" /* PRODUCTION */: + case TEEMode2.PRODUCTION: endpoint = void 0; - elizaLogger2.log( - "TEE: Running in production mode without simulator" - ); + logger3.log("TEE: Running in production mode without simulator"); break; default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); + throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); } this.client = endpoint ? new TappdClient2(endpoint) : new TappdClient2(); - this.raProvider = new RemoteAttestationProvider(teeMode); + this.raProvider = new PhalaRemoteAttestationProvider(teeMode); } async generateDeriveKeyAttestation(agentId, publicKey, subject) { const deriveKeyData = { @@ -1395,11 +267,9 @@ var DeriveKeyProvider = class { subject }; const reportdata = JSON.stringify(deriveKeyData); - elizaLogger2.log( - "Generating Remote Attestation Quote for Derive Key..." - ); + logger3.log("Generating Remote Attestation Quote for Derive Key..."); const quote = await this.raProvider.generateAttestation(reportdata); - elizaLogger2.log("Remote Attestation Quote generated successfully!"); + logger3.log("Remote Attestation Quote generated successfully!"); return quote; } /** @@ -1411,16 +281,14 @@ var DeriveKeyProvider = class { async rawDeriveKey(path, subject) { try { if (!path || !subject) { - elizaLogger2.error( - "Path and Subject are required for key derivation" - ); + logger3.error("Path and Subject are required for key derivation"); } - elizaLogger2.log("Deriving Raw Key in TEE..."); + logger3.log("Deriving Raw Key in TEE..."); const derivedKey = await this.client.deriveKey(path, subject); - elizaLogger2.log("Raw Key Derived Successfully!"); + logger3.log("Raw Key Derived Successfully!"); return derivedKey; } catch (error) { - elizaLogger2.error("Error deriving raw key:", error); + logger3.error("Error deriving raw key:", error); throw error; } } @@ -1434,26 +302,19 @@ var DeriveKeyProvider = class { async deriveEd25519Keypair(path, subject, agentId) { try { if (!path || !subject) { - elizaLogger2.error( - "Path and Subject are required for key derivation" - ); + logger3.error("Path and Subject are required for key derivation"); } - elizaLogger2.log("Deriving Key in TEE..."); + logger3.log("Deriving Key in TEE..."); const derivedKey = await this.client.deriveKey(path, subject); - const uint8ArrayDerivedKey = derivedKey.asUint8Array(); - const hash = crypto.createHash("sha256"); - hash.update(uint8ArrayDerivedKey); - const seed = hash.digest(); - const seedArray = new Uint8Array(seed); - const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); + const keypair = toKeypair(derivedKey); const attestation = await this.generateDeriveKeyAttestation( agentId, keypair.publicKey.toBase58() ); - elizaLogger2.log("Key Derived Successfully!"); + logger3.log("Key Derived Successfully!"); return { keypair, attestation }; } catch (error) { - elizaLogger2.error("Error deriving key:", error); + logger3.error("Error deriving key:", error); throw error; } } @@ -1467,175 +328,164 @@ var DeriveKeyProvider = class { async deriveEcdsaKeypair(path, subject, agentId) { try { if (!path || !subject) { - elizaLogger2.error( - "Path and Subject are required for key derivation" - ); + logger3.error("Path and Subject are required for key derivation"); } - elizaLogger2.log("Deriving ECDSA Key in TEE..."); + logger3.log("Deriving ECDSA Key in TEE..."); const deriveKeyResponse = await this.client.deriveKey(path, subject); - const hex = keccak256(deriveKeyResponse.asUint8Array()); - const keypair = privateKeyToAccount(hex); - const attestation = await this.generateDeriveKeyAttestation( - agentId, - keypair.address - ); - elizaLogger2.log("ECDSA Key Derived Successfully!"); + const keypair = toViemAccount(deriveKeyResponse); + const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address); + logger3.log("ECDSA Key Derived Successfully!"); return { keypair, attestation }; } catch (error) { - elizaLogger2.error("Error deriving ecdsa key:", error); + logger3.error("Error deriving ecdsa key:", error); throw error; } } }; -var deriveKeyProvider = { - get: async (runtime, _message, _state) => { +var phalaDeriveKeyProvider = { + name: "phala-derive-key", + get: async (runtime, _message) => { const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new DeriveKeyProvider(teeMode); + const provider = new PhalaDeriveKeyProvider(teeMode); const agentId = runtime.agentId; try { if (!runtime.getSetting("WALLET_SECRET_SALT")) { - elizaLogger2.error( - "Wallet secret salt is not configured in settings" - ); - return ""; + logger3.error("Wallet secret salt is not configured in settings"); + return { + data: null, + values: {}, + text: "Wallet secret salt is not configured in settings" + }; } try { const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; - const solanaKeypair = await provider.deriveEd25519Keypair( - secretSalt, - "solana", - agentId - ); - const evmKeypair = await provider.deriveEcdsaKeypair( - secretSalt, - "evm", - agentId - ); - return JSON.stringify({ + const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, "solana", agentId); + const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, "evm", agentId); + const walletData = { solana: solanaKeypair.keypair.publicKey, evm: evmKeypair.keypair.address - }); + }; + const values = { + solana_public_key: solanaKeypair.keypair.publicKey.toString(), + evm_address: evmKeypair.keypair.address + }; + const text = `Solana Public Key: ${values.solana_public_key} +EVM Address: ${values.evm_address}`; + return { + data: walletData, + values, + text + }; } catch (error) { - elizaLogger2.error("Error creating PublicKey:", error); - return ""; + logger3.error("Error creating PublicKey:", error); + return { + data: null, + values: {}, + text: `Error creating PublicKey: ${error instanceof Error ? error.message : "Unknown error"}` + }; } } catch (error) { - elizaLogger2.error("Error in derive key provider:", error.message); - return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`; + logger3.error("Error in derive key provider:", error.message); + return { + data: null, + values: {}, + text: `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}` + }; } } }; -// src/actions/remoteAttestation.ts -import { fetch } from "undici"; -function hexToUint8Array(hex) { - hex = hex.trim(); - if (!hex) { - throw new Error("Invalid hex string"); +// src/vendors/phala.ts +var PhalaVendor = class { + type = TeeVendorNames.PHALA; + /** + * Returns an array of actions. + * + * @returns {Array} An array containing the remote attestation action. + */ + getActions() { + return [phalaRemoteAttestationAction]; } - if (hex.startsWith("0x")) { - hex = hex.substring(2); + /** + * Retrieve the list of providers. + * + * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider. + */ + getProviders() { + return [phalaDeriveKeyProvider, phalaRemoteAttestationProvider]; } - if (hex.length % 2 !== 0) { - throw new Error("Invalid hex string"); + /** + * Returns the name of the plugin. + * @returns {string} The name of the plugin. + */ + getName() { + return "phala-tee-plugin"; } - const array = new Uint8Array(hex.length / 2); - for (let i = 0; i < hex.length; i += 2) { - const byte = Number.parseInt(hex.slice(i, i + 2), 16); - if (isNaN(byte)) { - throw new Error("Invalid hex string"); - } - array[i / 2] = byte; + /** + * Get the description of the function + * @returns {string} The description of the function + */ + getDescription() { + return "Phala TEE Cloud to Host Eliza Agents"; } - return array; -} -async function uploadUint8Array(data) { - const blob = new Blob([data], { type: "application/octet-stream" }); - const formData = new FormData(); - formData.append("file", blob, "quote.bin"); - return await fetch("https://proof.t16z.com/api/upload", { - method: "POST", - body: formData - }); -} -var remoteAttestationAction = { - name: "REMOTE_ATTESTATION", - similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"], - description: "Generate a remote attestation to prove that the agent is running in a TEE", - handler: async (runtime, message, _state, _options, callback) => { - try { - const attestationMessage = { - agentId: runtime.agentId, - timestamp: Date.now(), - message: { - userId: message.userId, - roomId: message.roomId, - content: message.content.text - } - }; - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new RemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); - const attestationData = hexToUint8Array(attestation.quote); - const response = await uploadUint8Array(attestationData); - const data = await response.json(); - callback({ - text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} -https://proof.t16z.com/reports/${data.checksum}`, - action: "NONE" - }); - return true; - } catch (error) { - console.error("Failed to fetch remote attestation: ", error); - return false; - } - }, - validate: async (_runtime) => { - return true; - }, - examples: [ - [ - { - user: "{{user1}}", - content: { - text: "If you are running in a TEE, generate a remote attestation", - action: "REMOTE_ATTESTATION" - } - }, - { - user: "{{user2}}", - content: { - text: "Of course, one second..." - } - } - ] - ] +}; + +// src/vendors/index.ts +var vendors = { + [TeeVendorNames.PHALA]: new PhalaVendor() +}; +var getVendor = (type) => { + const vendor = vendors[type]; + if (!vendor) { + throw new Error(`Unsupported TEE vendor type: ${type}`); + } + return vendor; }; // src/index.ts -var teePlugin = { - name: "tee", - description: "TEE plugin with actions to generate remote attestations and derive keys", - actions: [ - /* custom actions */ - remoteAttestationAction - ], - evaluators: [ - /* custom evaluators */ - ], - providers: [ - /* custom providers */ - remoteAttestationProvider, - deriveKeyProvider - ], - services: [ - /* custom services */ - ] +async function initializeTEE(config, runtime) { + if (config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR")) { + const vendor = config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR"); + logger4.info(`Initializing TEE with vendor: ${vendor}`); + let plugin; + switch (vendor) { + case "phala": + plugin = teePlugin({ + vendor: TeeVendorNames.PHALA + }); + break; + default: + throw new Error(`Invalid TEE vendor: ${vendor}`); + } + logger4.info(`Pushing plugin: ${plugin.name}`); + runtime.plugins.push(plugin); + } +} +var teePlugin = (config) => { + const vendorType = config?.vendor || TeeVendorNames.PHALA; + const vendor = getVendor(vendorType); + return { + name: vendor.getName(), + init: async (config2, runtime) => { + return await initializeTEE( + { + ...config2, + vendor: vendorType + }, + runtime + ); + }, + description: vendor.getDescription(), + actions: vendor.getActions(), + evaluators: [], + providers: vendor.getProviders(), + services: [] + }; }; export { - DeriveKeyProvider, - RemoteAttestationProvider, - TEEMode, + PhalaDeriveKeyProvider, + PhalaRemoteAttestationProvider, + phalaRemoteAttestationAction, teePlugin }; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index 40b877d..ee0cdf0 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/providers/remoteAttestationProvider.ts","../src/types/tee.ts","../src/providers/deriveKeyProvider.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/viem/node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/accounts/toAccount.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/accounts/utils/sign.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../../../node_modules/viem/accounts/utils/signAuthorization.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/accounts/privateKeyToAccount.ts","../src/actions/remoteAttestation.ts","../src/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { type TdxQuoteResponse, TappdClient, type TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\nimport { type RemoteAttestationQuote, TEEMode, type RemoteAttestationMessage } from \"../types/tee\";\n\nclass RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n elizaLogger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse =\n await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n elizaLogger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n elizaLogger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst remoteAttestationProvider: Provider = {\n get: async (runtime: IAgentRuntime, message: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n userId: message.userId,\n roomId: message.roomId,\n content: message.content.text,\n }\n };\n elizaLogger.log(\"Generating attestation for: \", JSON.stringify(attestationMessage));\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`;\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`\n );\n }\n },\n};\n\nexport { remoteAttestationProvider, RemoteAttestationProvider };\n","export enum TEEMode {\n OFF = \"OFF\",\n LOCAL = \"LOCAL\", // For local development with simulator\n DOCKER = \"DOCKER\", // For docker development with simulator\n PRODUCTION = \"PRODUCTION\", // For production without simulator\n}\n\nexport interface RemoteAttestationQuote {\n quote: string;\n timestamp: number;\n}\n\nexport interface DeriveKeyAttestationData {\n agentId: string;\n publicKey: string;\n subject?: string;\n}\n\nexport interface RemoteAttestationMessage {\n agentId: string;\n timestamp: number;\n message: {\n userId: string;\n roomId: string;\n content: string;\n }\n}","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n elizaLogger,\n} from \"@elizaos/core\";\nimport { Keypair } from \"@solana/web3.js\";\nimport crypto from \"crypto\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { type PrivateKeyAccount, keccak256 } from \"viem\";\nimport { RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { TEEMode, type RemoteAttestationQuote, type DeriveKeyAttestationData } from \"../types/tee\";\n\nclass DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n elizaLogger.log(\n \"TEE: Connecting to local simulator at localhost:8090\"\n );\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n elizaLogger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n elizaLogger.log(\n \"TEE: Running in production mode without simulator\"\n );\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n elizaLogger.log(\n \"Generating Remote Attestation Quote for Derive Key...\"\n );\n const quote = await this.raProvider.generateAttestation(reportdata);\n elizaLogger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n elizaLogger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n elizaLogger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const uint8ArrayDerivedKey = derivedKey.asUint8Array();\n\n const hash = crypto.createHash(\"sha256\");\n hash.update(uint8ArrayDerivedKey);\n const seed = hash.digest();\n const seedArray = new Uint8Array(seed);\n const keypair = Keypair.fromSeed(seedArray.slice(0, 32));\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n elizaLogger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n elizaLogger.error(\n \"Path and Subject are required for key derivation\"\n );\n }\n\n elizaLogger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse =\n await this.client.deriveKey(path, subject);\n const hex = keccak256(deriveKeyResponse.asUint8Array());\n const keypair: PrivateKeyAccount = privateKeyToAccount(hex);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n elizaLogger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n elizaLogger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\nconst deriveKeyProvider: Provider = {\n get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new DeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n elizaLogger.error(\n \"Wallet secret salt is not configured in settings\"\n );\n return \"\";\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n secretSalt,\n \"solana\",\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n secretSalt,\n \"evm\",\n agentId\n );\n return JSON.stringify({\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n });\n } catch (error) {\n elizaLogger.error(\"Error creating PublicKey:\", error);\n return \"\";\n }\n } catch (error) {\n elizaLogger.error(\"Error in derive key provider:\", error.message);\n return `Failed to fetch derive key information: ${error instanceof Error ? error.message : \"Unknown error\"}`;\n }\n },\n};\n\nexport { deriveKeyProvider, DeriveKeyProvider };\n","import { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = 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 // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per late 2024.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount(\n source: accountSource,\n): GetAccountReturnType {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n experimental_signAuthorization: source.experimental_signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters): SerializeSignatureReturnType {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType\n return hexToBytes(signature) as SerializeSignatureReturnType\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType = NumberToHexErrorType | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters): Promise> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n { lowS: true, extraEntropy },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray = T | readonly RecursiveArray[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp(\n bytes: RecursiveArray | RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType\n return cursor.bytes as ToRlpReturnType\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp(\n bytes: RecursiveArray,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp(\n hex: RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray | RecursiveArray,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization(\n parameters: HashAuthorizationParameters,\n): HashAuthorizationReturnType {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType\n return hash as HashAuthorizationReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../../experimental/eip7702/types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../experimental/eip7702/utils/hashAuthorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters =\n Authorization & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function experimental_signAuthorization(\n parameters: SignAuthorizationParameters,\n): Promise> {\n const {\n contractAddress,\n chainId,\n nonce,\n privateKey,\n to = 'object',\n } = parameters\n const signature = await sign({\n hash: hashAuthorization({ contractAddress, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n contractAddress,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n type HashMessageErrorType,\n hashMessage,\n} from '../../utils/signature/hashMessage.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n /** The message to sign. */\n message: SignableMessage\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n | SignErrorType\n | HashMessageErrorType\n | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n message,\n privateKey,\n}: SignMessageParameters): Promise {\n return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters,\n): BlobsToCommitmentsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters,\n): blobsToProofsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType\n}\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\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 Sha256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash\n return toHex(bytes) as Sha256Hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters,\n): CommitmentToVersionedHashReturnType {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters,\n): CommitmentsToVersionedHashesReturnType {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters): ToBlobsReturnType {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType =\n | (to extends 'bytes' ? BlobSidecars : never)\n | (to extends 'hex' ? BlobSidecars : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters,\n): ToBlobSidecarsReturnType {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract\n : never),\n> = IsNever extends true\n ? string\n : IsNever extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType {\n if (transaction.type)\n return transaction.type as GetTransactionType\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial,\n ExactPartial &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n type SerializeTransactionFn,\n serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n> = TransactionSerialized>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn = SerializeTransactionFn,\n transaction extends Parameters[0] = Parameters[0],\n>(\n parameters: SignTransactionParameters,\n): Promise> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(serializer(signableTransaction)),\n privateKey,\n })\n return serializer(transaction, signature) as SignTransactionReturnType<\n serializer,\n transaction\n >\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n typeof domain?.chainId === 'number' && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record\n primaryType: string\n types: Record\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record\n },\n results: Set = new Set(),\n): Set {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition & {\n /** The private key to sign with. */\n privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | HashTypedDataErrorType\n | SignErrorType\n | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters,\n): Promise {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { NonceManager } from '../utils/nonceManager.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n type PublicKeyToAddressErrorType,\n publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignErrorType, sign } from './utils/sign.js'\nimport { experimental_signAuthorization } from './utils/signAuthorization.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n type SignTransactionErrorType,\n signTransaction,\n} from './utils/signTransaction.js'\nimport {\n type SignTypedDataErrorType,\n signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\n | SignMessageErrorType\n | SignTransactionErrorType\n | SignTypedDataErrorType\n | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async experimental_signAuthorization(authorization) {\n return experimental_signAuthorization({ ...authorization, privateKey })\n },\n async signMessage({ message }) {\n return signMessage({ message, privateKey })\n },\n async signTransaction(transaction, { serializer } = {}) {\n return signTransaction({ privateKey, transaction, serializer })\n },\n async signTypedData(typedData) {\n return signTypedData({ ...typedData, privateKey } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","import type { IAgentRuntime, Memory, State, HandlerCallback } from \"@elizaos/core\";\nimport { RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { fetch, type BodyInit } from \"undici\";\nimport type { RemoteAttestationMessage } from \"../types/tee\";\n\nfunction hexToUint8Array(hex: string) {\n hex = hex.trim();\n if (!hex) {\n throw new Error(\"Invalid hex string\");\n }\n if (hex.startsWith(\"0x\")) {\n hex = hex.substring(2);\n }\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n const byte = Number.parseInt(hex.slice(i, i + 2), 16);\n if (isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, 'quote.bin');\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\nexport const remoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\"REMOTE_ATTESTATION\", \"TEE_REMOTE_ATTESTATION\", \"TEE_ATTESTATION\"],\n description: \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback,\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n userId: message.userId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n callback({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n action: \"NONE\",\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n user: \"{{user1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n action: \"REMOTE_ATTESTATION\",\n },\n },\n {\n user: \"{{user2}}\",\n content: {\n text: \"Of course, one second...\",\n },\n }\n ],\n ],\n};\n","import type { Plugin } from \"@elizaos/core\";\nimport { remoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nimport { deriveKeyProvider } from \"./providers/deriveKeyProvider\";\nimport { remoteAttestationAction } from \"./actions/remoteAttestation\";\n\nexport { DeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { RemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport { RemoteAttestationQuote, TEEMode } from \"./types/tee\";\n\nexport const teePlugin: Plugin = {\n name: \"tee\",\n description:\n \"TEE plugin with actions to generate remote attestations and derive keys\",\n actions: [\n /* custom actions */\n remoteAttestationAction,\n ],\n evaluators: [\n /* custom evaluators */\n ],\n providers: [\n /* custom providers */\n remoteAttestationProvider,\n deriveKeyProvider,\n ],\n services: [\n /* custom services */\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKI;AAAA,OACG;AACP,SAAgC,mBAAgD;;;ACPzE,IAAK,UAAL,kBAAKA,aAAL;AACH,EAAAA,SAAA,SAAM;AACN,EAAAA,SAAA,WAAQ;AACR,EAAAA,SAAA,YAAS;AACT,EAAAA,SAAA,gBAAa;AAJL,SAAAA;AAAA,GAAA;;;ADUZ,IAAM,4BAAN,MAAgC;AAAA,EACpB;AAAA,EAER,YAAY,SAAkB;AAC1B,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACb;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,mBAAW;AACX,oBAAY;AAAA,UACR;AAAA,QACJ;AACA;AAAA,MACJ;AACI,cAAM,IAAI;AAAA,UACN,qBAAqB,OAAO;AAAA,QAChC;AAAA,IACR;AAEA,SAA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AAQ,QAAQ;AAAA,UAChB,QAAQ,QAAQ;AAAA,UAChB,SAAS,QAAQ,QAAQ;AAAA,QAC7B;AAAA,MACJ;AAEA,YAAM,UAAU,QAAQ,WAAW,UAAU;AAC7C,YAAM,WAAW,IAAI,0BAA0B,OAAO;AAEtD,YAAM,cAAc,MAAM,SAAS,oBAAoB,KAAK,UAAU,kBAAkB,CAAC;AACzF,YAAM,kBAAkB,gBAAgB,YAAY,KAAK;AACzD,YAAM,WAAW,MAAM,iBAAiB,eAAe;AACvD,YAAM,OAAO,MAAM,SAAS,KAAK;AACjC,eAAS;AAAA,QACL,MAAM;AAAA,iCACW,KAAK,QAAQ;AAAA,QAC9B,QAAQ;AAAA,MACZ,CAAC;AACD,aAAO;AAAA,IACX,SAAS,OAAO;AACZ,cAAQ,MAAM,wCAAwC,KAAK;AAC3D,aAAO;AAAA,IACX;AAAA,EACJ;AAAA,EACA,UAAU,OAAO,aAA4B;AACzC,WAAO;AAAA,EACX;AAAA,EACA,UAAU;AAAA,IACN;AAAA,MACI;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,UACN,QAAQ;AAAA,QACZ;AAAA,MACJ;AAAA,MACA;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;;;AC3FO,IAAM,YAAoB;AAAA,EAC7B,MAAM;AAAA,EACN,aACI;AAAA,EACJ,SAAS;AAAA;AAAA,IAEL;AAAA,EACJ;AAAA,EACA,YAAY;AAAA;AAAA,EAEZ;AAAA,EACA,WAAW;AAAA;AAAA,IAEP;AAAA,IACA;AAAA,EACJ;AAAA,EACA,UAAU;AAAA;AAAA,EAEV;AACJ;","names":["TEEMode","elizaLogger","TappdClient","sha256","toBytes","sha256","size","size","blobs","commitments","proofs","v","struct","elizaLogger","TappdClient"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/vendors/types.ts","../src/actions/remoteAttestationAction.ts","../src/providers/remoteAttestationProvider.ts","../src/providers/base.ts","../src/utils.ts","../src/providers/deriveKeyProvider.ts","../src/vendors/phala.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Plugin,\n type TeePluginConfig,\n type TeeVendorConfig,\n logger,\n} from '@elizaos/core';\nimport { TeeVendorNames } from './vendors/types';\nimport { getVendor } from './vendors/index';\n\nexport { phalaRemoteAttestationAction } from './actions/remoteAttestationAction';\nexport { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider';\nexport { PhalaRemoteAttestationProvider } from './providers/remoteAttestationProvider';\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(config: Record, runtime: IAgentRuntime) {\n if (config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR')) {\n const vendor = config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR');\n logger.info(`Initializing TEE with vendor: ${vendor}`);\n let plugin: Plugin;\n switch (vendor) {\n case 'phala':\n plugin = teePlugin({\n vendor: TeeVendorNames.PHALA,\n });\n break;\n default:\n throw new Error(`Invalid TEE vendor: ${vendor}`);\n }\n logger.info(`Pushing plugin: ${plugin.name}`);\n runtime.plugins.push(plugin);\n }\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n const vendorType = config?.vendor || TeeVendorNames.PHALA;\n const vendor = getVendor(vendorType);\n return {\n name: vendor.getName(),\n init: async (config: Record, runtime: IAgentRuntime) => {\n return await initializeTEE(\n {\n ...config,\n vendor: vendorType,\n },\n runtime\n );\n },\n description: vendor.getDescription(),\n actions: vendor.getActions(),\n evaluators: [],\n providers: vendor.getProviders(),\n services: [],\n };\n};\n","import type { Action, Provider } from '@elizaos/core';\n\nexport const TeeVendorNames = {\n PHALA: 'phala',\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName = (typeof TeeVendorNames)[keyof typeof TeeVendorNames] | string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n type: TeeVendorName;\n getActions(): Action[];\n getProviders(): Provider[];\n getName(): string;\n getDescription(): string;\n}\n","import type {\n HandlerCallback,\n IAgentRuntime,\n Memory,\n RemoteAttestationMessage,\n State,\n} from '@elizaos/core';\nimport { logger } from '@elizaos/core';\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from '../providers/remoteAttestationProvider';\nimport { hexToUint8Array } from '../utils';\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: 'application/octet-stream' });\n const formData = new FormData();\n formData.append('file', blob, 'quote.bin');\n\n return await fetch('https://proof.t16z.com/api/upload', {\n method: 'POST',\n body: formData as BodyInit,\n });\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}}\n */\nexport const phalaRemoteAttestationAction = {\n name: 'REMOTE_ATTESTATION',\n similes: [\n 'REMOTE_ATTESTATION',\n 'TEE_REMOTE_ATTESTATION',\n 'TEE_ATTESTATION',\n 'TEE_QUOTE',\n 'ATTESTATION',\n 'TEE_ATTESTATION_QUOTE',\n ],\n description: 'Generate a remote attestation to prove that the agent is running in a TEE',\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting('TEE_MODE');\n logger.debug(`Tee mode: ${teeMode}`);\n logger.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`);\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n\n callback({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n actions: ['NONE'],\n });\n return true;\n } catch (error) {\n console.error('Failed to fetch remote attestation: ', error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n name: '{{name1}}',\n content: {\n text: 'If you are running in a TEE, generate a remote attestation',\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'Of course, one second...',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n [\n {\n name: '{{name1}}',\n content: {\n text: 'Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?',\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n [\n {\n name: '{{name1}}',\n content: {\n text: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'Oh, dear...lemme find that for you',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n ],\n};\n","import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core';\nimport { type RemoteAttestationMessage, type RemoteAttestationQuote, TEEMode } from '@elizaos/core';\nimport { TappdClient, type TdxQuoteHashAlgorithms, type TdxQuoteResponse } from '@phala/dstack-sdk';\nimport { RemoteAttestationProvider } from './base';\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = 'http://localhost:8090';\n logger.log('TEE: Connecting to local simulator at localhost:8090');\n break;\n case TEEMode.DOCKER:\n endpoint = 'http://host.docker.internal:8090';\n logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090');\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log('TEE: Running in production mode without simulator');\n break;\n default:\n throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`);\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n logger.log('Generating attestation for: ', reportData);\n const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n logger.log(`rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`);\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n logger.log('Remote attestation quote: ', quote);\n return quote;\n } catch (error) {\n console.error('Error generating remote attestation:', error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n name: 'phala-remote-attestation',\n get: async (runtime: IAgentRuntime, message: Memory) => {\n const teeMode = runtime.getSetting('TEE_MODE');\n const provider = new PhalaRemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n logger.log('Generating attestation for: ', JSON.stringify(attestationMessage));\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n return {\n text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`,\n data: {\n attestation,\n },\n values: {\n quote: attestation.quote,\n timestamp: attestation.timestamp.toString(),\n },\n };\n } catch (error) {\n console.error('Error in remote attestation provider:', error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n },\n};\n\nexport { phalaRemoteAttestationProvider, PhalaRemoteAttestationProvider };\n","import type { RemoteAttestationQuote } from '@elizaos/core';\nimport type { TdxQuoteHashAlgorithms } from '@phala/dstack-sdk';\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n abstract generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise;\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n const hexString = hex.trim().replace(/^0x/, '');\n if (!hexString) {\n throw new Error('Invalid hex string');\n }\n if (hexString.length % 2 !== 0) {\n throw new Error('Invalid hex string');\n }\n\n const array = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n const byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error('Invalid hex string');\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n const hash = createHash('sha256');\n hash.update(input);\n return hash.digest();\n}\n","import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core';\nimport { type DeriveKeyAttestationData, type RemoteAttestationQuote, TEEMode } from '@elizaos/core';\nimport { type DeriveKeyResponse, TappdClient } from '@phala/dstack-sdk';\nimport { Keypair } from '@solana/web3.js';\nimport { toViemAccount } from '@phala/dstack-sdk/viem';\nimport { toKeypair } from '@phala/dstack-sdk/solana';\nimport { DeriveKeyProvider } from './base';\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from './remoteAttestationProvider';\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = 'http://localhost:8090';\n logger.log('TEE: Connecting to local simulator at localhost:8090');\n break;\n case TEEMode.DOCKER:\n endpoint = 'http://host.docker.internal:8090';\n logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090');\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log('TEE: Running in production mode without simulator');\n break;\n default:\n throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`);\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n logger.log('Generating Remote Attestation Quote for Derive Key...');\n const quote = await this.raProvider.generateAttestation(reportdata);\n logger.log('Remote Attestation Quote generated successfully!');\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(path: string, subject: string): Promise {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving Raw Key in TEE...');\n const derivedKey = await this.client.deriveKey(path, subject);\n\n logger.log('Raw Key Derived Successfully!');\n return derivedKey;\n } catch (error) {\n logger.error('Error deriving raw key:', error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving Key in TEE...');\n const derivedKey = await this.client.deriveKey(path, subject);\n const keypair = toKeypair(derivedKey);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n logger.log('Key Derived Successfully!');\n\n return { keypair, attestation };\n } catch (error) {\n logger.error('Error deriving key:', error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving ECDSA Key in TEE...');\n const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(path, subject);\n const keypair = toViemAccount(deriveKeyResponse);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address);\n logger.log('ECDSA Key Derived Successfully!');\n\n return { keypair, attestation };\n } catch (error) {\n logger.error('Error deriving ecdsa key:', error);\n throw error;\n }\n }\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n name: 'phala-derive-key',\n get: async (runtime: IAgentRuntime, _message?: Memory): Promise => {\n const teeMode = runtime.getSetting('TEE_MODE');\n const provider = new PhalaDeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting('WALLET_SECRET_SALT')) {\n logger.error('Wallet secret salt is not configured in settings');\n return {\n data: null,\n values: {},\n text: 'Wallet secret salt is not configured in settings',\n };\n }\n\n try {\n const secretSalt = runtime.getSetting('WALLET_SECRET_SALT') || 'secret_salt';\n const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, 'solana', agentId);\n const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, 'evm', agentId);\n\n // Original data structure\n const walletData = {\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n };\n\n // Values for template injection\n const values = {\n solana_public_key: solanaKeypair.keypair.publicKey.toString(),\n evm_address: evmKeypair.keypair.address,\n };\n\n // Text representation\n const text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n return {\n data: walletData,\n values: values,\n text: text,\n };\n } catch (error) {\n logger.error('Error creating PublicKey:', error);\n return {\n data: null,\n values: {},\n text: `Error creating PublicKey: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n };\n }\n } catch (error) {\n logger.error('Error in derive key provider:', error.message);\n return {\n data: null,\n values: {},\n text: `Failed to fetch derive key information: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n };\n }\n },\n};\n\nexport { phalaDeriveKeyProvider, PhalaDeriveKeyProvider };\n","import { phalaRemoteAttestationAction as remoteAttestationAction } from '../actions/remoteAttestationAction';\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from '../providers/deriveKeyProvider';\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from '../providers/remoteAttestationProvider';\nimport { type TeeVendor, TeeVendorNames } from './types';\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendorNames.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n type = TeeVendorNames.PHALA;\n\n /**\n * Returns an array of actions.\n *\n * @returns {Array} An array containing the remote attestation action.\n */\n getActions() {\n return [remoteAttestationAction];\n }\n /**\n * Retrieve the list of providers.\n *\n * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n */\n getProviders() {\n return [deriveKeyProvider, remoteAttestationProvider];\n }\n\n /**\n * Returns the name of the plugin.\n * @returns {string} The name of the plugin.\n */\n getName() {\n return 'phala-tee-plugin';\n }\n\n /**\n * Get the description of the function\n * @returns {string} The description of the function\n */\n getDescription() {\n return 'Phala TEE Cloud to Host Eliza Agents';\n }\n}\n","import { PhalaVendor } from './phala';\nimport type { TeeVendor } from './types';\nimport { type TeeVendorName, TeeVendorNames } from './types';\n\nconst vendors: Record = {\n [TeeVendorNames.PHALA]: new PhalaVendor(),\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n const vendor = vendors[type];\n if (!vendor) {\n throw new Error(`Unsupported TEE vendor type: ${type}`);\n }\n return vendor;\n};\n\nexport * from './types';\n"],"mappings":";AAAA;AAAA,EAKE,UAAAA;AAAA,OACK;;;ACJA,IAAM,iBAAiB;AAAA,EAC5B,OAAO;AACT;;;ACGA,SAAS,UAAAC,eAAc;;;ACPvB,SAAyD,cAAc;AACv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Client","logger","config"]} \ No newline at end of file diff --git a/dist/secp256k1-QUTB2QC2.js b/dist/secp256k1-QUTB2QC2.js deleted file mode 100644 index 0b1762d..0000000 --- a/dist/secp256k1-QUTB2QC2.js +++ /dev/null @@ -1,14 +0,0 @@ -import { - encodeToCurve, - hashToCurve, - schnorr, - secp256k1 -} from "./chunk-4L6P6TY5.js"; -import "./chunk-PR4QN5HX.js"; -export { - encodeToCurve, - hashToCurve, - schnorr, - secp256k1 -}; -//# sourceMappingURL=secp256k1-QUTB2QC2.js.map \ No newline at end of file diff --git a/dist/secp256k1-QUTB2QC2.js.map b/dist/secp256k1-QUTB2QC2.js.map deleted file mode 100644 index 84c51b2..0000000 --- a/dist/secp256k1-QUTB2QC2.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/images/banner.jpg b/images/banner.jpg deleted file mode 100644 index a80d90701fd21f3bd00f4690fc44771e94a4ecd3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12636 zcmbVy2~-raO5FSxroIE8vBUh7_F>U&+fo?C3opRGmPao)(7#bHCXB?W5IX!0n z?2K{qN9m``&z{mR-7R8}CcL13!A#@KjNHkZf|)aB&FNn-(CyF0`_u28#Q|=bKda5HCaj--TG*66AycMI?dPir4h#+n2n-7d>f;v_ z+`o6f{(&Kye_d|0!`bOm`;Uzr_OI^fuYqp=npb{)zJGpi|D4&=0)qPW>lY9h91tAr zM{D@anKvtUa)IBhIqrY85ScM&%IxXJ-03;9G@UI@PRq&59q2{}`(Lw|X^e~ecf9OD3$)T(|Y^$4Gik%*SB}? zwDdk9!J!#}p?|gWpPug>+P8ODpU6IuLj!|?f}(~E4jdd5HF#*>A${zGSHOwP@jtca{JBONR(5DVmMV3{nABAx4Ed8ekJ31au_y^REj@ zWfBX_$yr+1dHq%1`4=&mRd#-23yx)FG7GNrHd46;4W5k0d{MNIVYzL#b`p!1-$`ZP z|MrKv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bsuc-fDLUQ&cfpnqF3P8` zoQ>0g)C}65jrKo-M!hkKE44)c^>T8PMspstDAVkx@f-_*T)II0;9SuEjdz+3SK;?2 zRO($NxXz#??h8Qc4V)MwjnP@I2!Ud(^1#$1_o4*j&$ z>V2uo7hg9?qD$%a)LInQN=_J@MXIl-p{Zr?4H_g$nU|z8SjPmXVfyytQP@>Qb~iEh zg3WGTLP1dzyMzi+P#I|Pj;c|UDE{^Eh2wfQ3ppaHM63D9FT9J32T%4CvrM)D6N{#b zp8KEh7tQJikgq>krz#HtIi=y_(&2xmthd&xJ=W(u9xj9^Ct&?U3cCrCus$ope)V7MH5T zE#vs1r%`k0m&+QSqGrz|{Dn$zZFaBMx2PU+DQ;|dq{&9@_zX3>x!2mL)LmvU4N<0X z4biw@!&v_B4NTsq$c48*Gm-@>_iBVQ3nMg)gWB6UC z9e3lb+s7c+FB$bLke2Zdsk;P+Q%RO$>Z4wfv94_Fn)voF z5bt$>{Pwyi@rJm??DEpDz1D4!W}qM({tz?9m-&$Lm`vEapTwpbY#)yqyTtM%AMlD~ z2pT4e_dmNPb%xZd4tJ?s zVRR;aAp}K~@8mSa+=L{H*Zki{ActbKm_(gAF5So{NyyIj+ArbgXAMt>Axkyk-xim` Oh|h-PgIr<9jsFAg?5`~V diff --git a/images/logo.jpg b/images/logo.jpg deleted file mode 100644 index fe96f2b7ad81a77c1ac0cee83cbf9d937b0f7f89..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6162 zcmaJ_2|SeB`#WQd`>$>OXO7aKc@DK~;m zVW`omEE-LNqRUWY>aujSSS){rDn)~)p`}jKRj2Dv=^FZ)41Jmw)V@| zf1M8N8Onc+D>^z_Em~8J8xf#RXD}G*G!1nP4Jsx<<;8L$ePgH`p29Z^W^5iSA}BmE zh|8fYTJ&XdqaqFEF=zjdA}rj-=DXp41uQIVF|;qzyhwZYKW_Z1G|wS6oULxp=5eDU zSZqvO;hQoB-+xcED2REZZyOPWt&4A{8J86m#^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t_Nh9Bw5>r06DVvnmMY;#fyKt5yIT!_g3H#rov#x!Ls^c@~ z^xs|U@6GspcCx&CGV8&Crh@^tx4mapch6j&EM4uoDvOoc{Bp=UX6C)_+q!2dRO6Bf zUWwE zqxVkOl?4LLU4nSOxXke@ERQC&nA<&%cDSr{db3t zjq1+R_yK#yK3vau7Bb1bEfkmJ{2=~%;qA-(%Vr|pr>_of{G4ep&b^JZeO{UHxMcyn z`Z8i%{NSF*a_corvjJC_w7P|*3bgi*@s%RQyvO69mk zH3t^GNkxoN!g6p7Wc>%?BQ&Yc!3^FFWQ`#ts+pBg@Fo;UGtP*qMJcJ2|^{j zpiF?0y`c0iQS5G>3bcf>#nCk3ohS?0Ylrs&%4mSF6xJODhd>0HiYTC3IO#@osSDZV z+)FBD0}v=2wUb~%U9b~@g(Uhc2Wi-?_kIQLImiUpe1HfjD+0n5I57f6%M4cp)fAJu zu?w=qO&8KLSlz!uSpk3^AYLJa5^4&6R5iR7AWIQCdNTFW~MFC_s;}>?Ev(I|1*3q^>7BQM6F=sv@9( z-2<~lI9Oca0GM|Z0)cp#K*cW4;F#=+hCkpM0$?B@gA5!{ zKu2ZaY$6PRs*EMc9T5h0qQ6qi?TZ|l7fs;CVX`AaFQS|)lE`*L5Ml$xO}Tgp9H+XEAg+MFhNoJSl)eF78r^0Sb<9P`?;}&n%*p!aCVxP>M(Z3lJ`>hKkHlU32KH8SNT3B`h)Tj}2&#Pv zP{RS7O}YWPV6i1nc$jV2OE5@_Km0Ka|lMF|zI zfWcW15e@=~LMMW-rI8yJ-w4+L5@Oc{#0csWC`#b2F`*#&6b7)n1BQuDQ}dIt?AQ

    t^G diff --git a/package.json b/package.json index 2d96ec7..c8fca7e 100644 --- a/package.json +++ b/package.json @@ -1,71 +1,45 @@ { - "name": "@elizaos-plugins/plugin-tee", - "version": "0.1.9", - "type": "module", - "main": "dist/index.js", - "module": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - "./package.json": "./package.json", - ".": { - "import": { - "@elizaos/source": "./src/index.ts", - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } - } - }, - "files": [ - "dist" - ], - "dependencies": { - "@phala/dstack-sdk": "0.1.7", - "@solana/spl-token": "0.4.9", - "@solana/web3.js": "1.95.8", - "bignumber.js": "9.1.2", - "bs58": "6.0.0", - "node-cache": "5.1.2", - "pumpdotfun-sdk": "1.3.2", - "tsup": "8.3.5" - }, - "devDependencies": { - "@biomejs/biome": "1.5.3", - "tsup": "^8.3.5" - }, - "scripts": { - "build": "tsup --format esm --dts", - "dev": "tsup --format esm --dts --watch", - "test": "vitest run", - "lint": "biome check src/", - "lint:fix": "biome check --apply src/", - "format": "biome format src/", - "format:fix": "biome format --write src/" - }, - "peerDependencies": { - "whatwg-url": "7.1.0" - }, - "agentConfig": { - "pluginType": "elizaos:client:1.0.0", - "pluginParameters": { - "TEE_MODE": { - "type": "string", - "enum": [ - "sgx", - "nitro", - "disabled" - ], - "description": "Trusted Execution Environment mode" - }, - "WALLET_SECRET_SALT": { - "type": "string", - "minLength": 1, - "description": "Salt for wallet secret generation" - }, - "BIRDEYE_API_KEY": { - "type": "string", - "minLength": 1, - "description": "API key for Birdeye service" - } + "name": "@elizaos/plugin-tee", + "version": "1.0.0-beta.49", + "main": "dist/index.js", + "type": "module", + "types": "dist/index.d.ts", + "dependencies": { + "@elizaos/core": "^1.0.0-beta.49", + "@phala/dstack-sdk": "0.1.11", + "@solana/web3.js": "1.98.0", + "viem": "2.23.11" + }, + "devDependencies": { + "@types/node": "^22.15.3", + "prettier": "3.5.3", + "tsup": "8.4.0", + "typescript": "5.8.2" + }, + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "lint": "prettier --write ./src", + "clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo", + "format": "prettier --write ./src", + "format:check": "prettier --check ./src" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "646c632924826e2b75c2304a75ee56959fe4a460", + "agentConfig": { + "pluginType": "elizaos:plugin:1.0.0", + "pluginParameters": { + "TEE_VENDOR": { + "type": "string" + }, + "TEE_MODE": { + "type": "string" + }, + "WALLET_SECRET_SALT": { + "type": "string" } } -} \ No newline at end of file + } +} diff --git a/src/.DS_Store b/src/.DS_Store deleted file mode 100644 index 4614bd24994135a65594c8a52917e6001c0a4598..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKOHRWu5FM8yQUOwzUFHhCK`7w_-Lil-rBrH2#7|-uiHmRo#0A)L0>lAWathwe zxM@NHLPA0a%}DlhCeQZEOBCBgf?=wdk^ zj;C3JZHd3=0KdB}I;JUI(t;}QFU?i%?n#r8W^p`OW)s{A9-jAKZttJ=+E~dqSotY` zEvwo1JER`vbPg@oP?XRNZU0TJSciA*tg5cZ*HTx@cxkrQ_BFGvPfXc_S2xf&`>3n4 zfUe5js-D4Hsi($R>u6`x=NEr4iG?{}4wwT!asX>KN3gAEwK-r8m;j1g(5Ntr(J>C)%hca)9%QJo)>v66tz1!nHl5wnVmnO zIKM-3q0q@iidLHg=0M$n4ZZC1`hW2G`M=)DuFL^*;9oi5y74$3;gS5>+ITo#YeSSH p6b|MUie(oxWGM!hm*N461o9y_fRV>S5gCMS1jGib%z ({ + TappdClient: vi.fn().mockImplementation(() => ({ + deriveKey: vi.fn().mockResolvedValue({ + asUint8Array: () => new Uint8Array([1, 2, 3, 4, 5]), + }), + tdxQuote: vi.fn().mockResolvedValue({ + quote: 'mock-quote-data', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + }), + rawDeriveKey: vi.fn(), + })), +})); + +vi.mock('@solana/web3.js', () => ({ + Keypair: { + fromSeed: vi.fn().mockReturnValue({ + publicKey: { + toBase58: () => 'mock-solana-public-key', + }, + }), + }, +})); + +vi.mock('viem/accounts', () => ({ + privateKeyToAccount: vi.fn().mockReturnValue({ + address: 'mock-evm-address', + }), +})); + +describe('DeriveKeyProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('constructor', () => { + it('should initialize with LOCAL mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + }); + + it('should initialize with DOCKER mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + }); + + it('should initialize with PRODUCTION mode', () => { + const _provider = new DeriveKeyProvider(TEEMode.PRODUCTION); + expect(TappdClient).toHaveBeenCalledWith(); + }); + + it('should throw error for invalid mode', () => { + expect(() => new DeriveKeyProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + }); + }); + + describe('rawDeriveKey', () => { + let _provider: DeriveKeyProvider; + + beforeEach(() => { + _provider = new DeriveKeyProvider(TEEMode.LOCAL); + }); + + it('should derive raw key successfully', async () => { + const path = 'test-path'; + const subject = 'test-subject'; + const result = await _provider.rawDeriveKey(path, subject); + + const client = TappdClient.mock.results[0].value; + expect(client.deriveKey).toHaveBeenCalledWith(path, subject); + expect(result.asUint8Array()).toEqual(new Uint8Array([1, 2, 3, 4, 5])); + }); + + it('should handle errors during raw key derivation', async () => { + const mockError = new Error('Key derivation failed'); + vi.mocked(TappdClient).mockImplementationOnce(() => { + const instance = new TappdClient(); + instance.deriveKey = vi.fn().mockRejectedValueOnce(mockError); + instance.tdxQuote = vi.fn(); + instance.rawDeriveKey = vi.fn(); + return instance; + }); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(provider.rawDeriveKey('path', 'subject')).rejects.toThrow(mockError); + }); + }); + + describe('deriveEd25519Keypair', () => { + let provider: DeriveKeyProvider; + + beforeEach(() => { + provider = new DeriveKeyProvider(TEEMode.LOCAL); + }); + + it('should derive Ed25519 keypair successfully', async () => { + const path = 'test-path'; + const subject = 'test-subject'; + const result = await provider.deriveEd25519Keypair(path, subject, 'test-agent-id'); + + const client = TappdClient.mock.results[0].value; + expect(client.deriveKey).toHaveBeenCalledWith(path, subject); + expect(result.keypair.publicKey.toBase58()).toEqual('mock-solana-public-key'); + }); + }); +}); diff --git a/src/__tests__/remoteAttestation.test.ts b/src/__tests__/remoteAttestation.test.ts new file mode 100644 index 0000000..740bfff --- /dev/null +++ b/src/__tests__/remoteAttestation.test.ts @@ -0,0 +1,83 @@ +import { TEEMode } from '@elizaos/core'; +import { TappdClient } from '@phala/dstack-sdk'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; + +// Mock TappdClient +vi.mock('@phala/dstack-sdk', () => ({ + TappdClient: vi.fn().mockImplementation(() => ({ + tdxQuote: vi.fn().mockResolvedValue({ + quote: 'mock-quote-data', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + }), + deriveKey: vi.fn(), + })), +})); + +describe('RemoteAttestationProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('constructor', () => { + it('should initialize with LOCAL mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + }); + + it('should initialize with DOCKER mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + }); + + it('should initialize with PRODUCTION mode', () => { + const _provider = new RemoteAttestationProvider(TEEMode.PRODUCTION); + expect(TappdClient).toHaveBeenCalledWith(); + }); + + it('should throw error for invalid mode', () => { + expect(() => new RemoteAttestationProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + }); + }); + + describe('generateAttestation', () => { + let provider: RemoteAttestationProvider; + + beforeEach(() => { + provider = new RemoteAttestationProvider(TEEMode.LOCAL); + }); + + it('should generate attestation successfully', async () => { + const reportData = 'test-report-data'; + const quote = await provider.generateAttestation(reportData); + + expect(quote).toEqual({ + quote: 'mock-quote-data', + timestamp: expect.any(Number), + }); + }); + + it('should handle errors during attestation generation', async () => { + const mockError = new Error('TDX Quote generation failed'); + const mockTdxQuote = vi.fn().mockRejectedValue(mockError); + vi.mocked(TappdClient).mockImplementationOnce(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(provider.generateAttestation('test-data')).rejects.toThrow( + 'Failed to generate TDX Quote' + ); + }); + + it('should pass hash algorithm to tdxQuote when provided', async () => { + const reportData = 'test-report-data'; + const hashAlgorithm = 'raw'; + await provider.generateAttestation(reportData, hashAlgorithm); + + const client = TappdClient.mock.results[0].value; + expect(client.tdxQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); + }); + }); +}); diff --git a/src/__tests__/timeout.test.ts b/src/__tests__/timeout.test.ts new file mode 100644 index 0000000..9fe7b24 --- /dev/null +++ b/src/__tests__/timeout.test.ts @@ -0,0 +1,113 @@ +import { TEEMode } from '@elizaos/core'; +import { TappdClient } from '@phala/dstack-sdk'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { DeriveKeyProvider } from '../providers/deriveKeyProvider'; +import { RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; + +// Mock TappdClient +vi.mock('@phala/dstack-sdk', () => ({ + TappdClient: vi.fn().mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: vi.fn(), + })), +})); + +describe('TEE Provider Timeout Tests', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('RemoteAttestationProvider', () => { + it('should handle API timeout during attestation generation', async () => { + const mockTdxQuote = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => provider.generateAttestation('test-data')).rejects.toThrow( + 'Failed to generate TDX Quote: Request timed out' + ); + + // Verify the call was made once + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + expect(mockTdxQuote).toHaveBeenCalledWith('test-data', undefined); + }); + + it('should handle network errors during attestation generation', async () => { + const mockTdxQuote = vi.fn().mockRejectedValueOnce(new Error('Network error')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => provider.generateAttestation('test-data')).rejects.toThrow( + 'Failed to generate TDX Quote: Network error' + ); + + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + }); + + it('should handle successful attestation generation', async () => { + const mockQuote = { + quote: 'test-quote', + replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + }; + + const mockTdxQuote = vi.fn().mockResolvedValueOnce(mockQuote); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + })); + + const provider = new RemoteAttestationProvider(TEEMode.LOCAL); + const result = await provider.generateAttestation('test-data'); + + expect(mockTdxQuote).toHaveBeenCalledTimes(1); + expect(result).toEqual({ + quote: 'test-quote', + timestamp: expect.any(Number), + }); + }); + }); + + describe('DeriveKeyProvider', () => { + it('should handle API timeout during key derivation', async () => { + const mockDeriveKey = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: mockDeriveKey, + })); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(() => provider.rawDeriveKey('test-path', 'test-subject')).rejects.toThrow( + 'Request timed out' + ); + + expect(mockDeriveKey).toHaveBeenCalledTimes(1); + expect(mockDeriveKey).toHaveBeenCalledWith('test-path', 'test-subject'); + }); + + it('should handle API timeout during Ed25519 key derivation', async () => { + const mockDeriveKey = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); + + vi.mocked(TappdClient).mockImplementation(() => ({ + tdxQuote: vi.fn(), + deriveKey: mockDeriveKey, + })); + + const provider = new DeriveKeyProvider(TEEMode.LOCAL); + await expect(() => + provider.deriveEd25519Keypair('test-path', 'test-subject') + ).rejects.toThrow('Request timed out'); + + expect(mockDeriveKey).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/src/actions/remoteAttestation.ts b/src/actions/remoteAttestation.ts deleted file mode 100644 index dd80e05..0000000 --- a/src/actions/remoteAttestation.ts +++ /dev/null @@ -1,101 +0,0 @@ -import type { IAgentRuntime, Memory, State, HandlerCallback } from "@elizaos/core"; -import { RemoteAttestationProvider } from "../providers/remoteAttestationProvider"; -import { fetch, type BodyInit } from "undici"; -import type { RemoteAttestationMessage } from "../types/tee"; - -function hexToUint8Array(hex: string) { - hex = hex.trim(); - if (!hex) { - throw new Error("Invalid hex string"); - } - if (hex.startsWith("0x")) { - hex = hex.substring(2); - } - if (hex.length % 2 !== 0) { - throw new Error("Invalid hex string"); - } - - const array = new Uint8Array(hex.length / 2); - for (let i = 0; i < hex.length; i += 2) { - const byte = Number.parseInt(hex.slice(i, i + 2), 16); - if (isNaN(byte)) { - throw new Error("Invalid hex string"); - } - array[i / 2] = byte; - } - return array; -} - -async function uploadUint8Array(data: Uint8Array) { - const blob = new Blob([data], { type: "application/octet-stream" }); - const formData = new FormData(); - formData.append("file", blob, 'quote.bin'); - - return await fetch("https://proof.t16z.com/api/upload", { - method: "POST", - body: formData as BodyInit, - }); -} - -export const remoteAttestationAction = { - name: "REMOTE_ATTESTATION", - similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"], - description: "Generate a remote attestation to prove that the agent is running in a TEE", - handler: async ( - runtime: IAgentRuntime, - message: Memory, - _state: State, - _options: { [key: string]: unknown }, - callback: HandlerCallback, - ) => { - try { - // Attestation will be generated based on the message info - const attestationMessage: RemoteAttestationMessage = { - agentId: runtime.agentId, - timestamp: Date.now(), - message: { - userId: message.userId, - roomId: message.roomId, - content: message.content.text, - }, - }; - // Get the remote attestation of the agentId - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new RemoteAttestationProvider(teeMode); - - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); - const attestationData = hexToUint8Array(attestation.quote); - const response = await uploadUint8Array(attestationData); - const data = await response.json(); - callback({ - text: `Here's my 🧾 RA Quote 🫡 -https://proof.t16z.com/reports/${data.checksum}`, - action: "NONE", - }); - return true; - } catch (error) { - console.error("Failed to fetch remote attestation: ", error); - return false; - } - }, - validate: async (_runtime: IAgentRuntime) => { - return true; - }, - examples: [ - [ - { - user: "{{user1}}", - content: { - text: "If you are running in a TEE, generate a remote attestation", - action: "REMOTE_ATTESTATION", - }, - }, - { - user: "{{user2}}", - content: { - text: "Of course, one second...", - }, - } - ], - ], -}; diff --git a/src/actions/remoteAttestationAction.ts b/src/actions/remoteAttestationAction.ts new file mode 100644 index 0000000..7ad0579 --- /dev/null +++ b/src/actions/remoteAttestationAction.ts @@ -0,0 +1,137 @@ +import type { + HandlerCallback, + IAgentRuntime, + Memory, + RemoteAttestationMessage, + State, +} from '@elizaos/core'; +import { logger } from '@elizaos/core'; +import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; +import { hexToUint8Array } from '../utils'; + +/** + * Asynchronously uploads a Uint8Array as a binary file to a specified URL. + * + * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file. + * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object. + */ +async function uploadUint8Array(data: Uint8Array) { + const blob = new Blob([data], { type: 'application/octet-stream' }); + const formData = new FormData(); + formData.append('file', blob, 'quote.bin'); + + return await fetch('https://proof.t16z.com/api/upload', { + method: 'POST', + body: formData as BodyInit, + }); +} + +/** + * Represents an action for remote attestation. + * + * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE). + * + * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}} + */ +export const phalaRemoteAttestationAction = { + name: 'REMOTE_ATTESTATION', + similes: [ + 'REMOTE_ATTESTATION', + 'TEE_REMOTE_ATTESTATION', + 'TEE_ATTESTATION', + 'TEE_QUOTE', + 'ATTESTATION', + 'TEE_ATTESTATION_QUOTE', + ], + description: 'Generate a remote attestation to prove that the agent is running in a TEE', + handler: async ( + runtime: IAgentRuntime, + message: Memory, + _state: State, + _options: { [key: string]: unknown }, + callback: HandlerCallback + ) => { + try { + // Attestation will be generated based on the message info + const attestationMessage: RemoteAttestationMessage = { + agentId: runtime.agentId, + timestamp: Date.now(), + message: { + entityId: message.entityId, + roomId: message.roomId, + content: message.content.text, + }, + }; + // Get the remote attestation of the agentId + const teeMode = runtime.getSetting('TEE_MODE'); + logger.debug(`Tee mode: ${teeMode}`); + logger.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`); + const provider = new RemoteAttestationProvider(teeMode); + + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + const attestationData = hexToUint8Array(attestation.quote); + const response = await uploadUint8Array(attestationData); + const data = await response.json(); + + callback({ + text: `Here's my 🧾 RA Quote 🫡 +https://proof.t16z.com/reports/${data.checksum}`, + actions: ['NONE'], + }); + return true; + } catch (error) { + console.error('Failed to fetch remote attestation: ', error); + return false; + } + }, + validate: async (_runtime: IAgentRuntime) => { + return true; + }, + examples: [ + [ + { + name: '{{name1}}', + content: { + text: 'If you are running in a TEE, generate a remote attestation', + }, + }, + { + name: '{{agentName}}', + content: { + text: 'Of course, one second...', + actions: ['REMOTE_ATTESTATION'], + }, + }, + ], + [ + { + name: '{{name1}}', + content: { + text: 'Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?', + }, + }, + { + name: '{{agentName}}', + content: { + text: 'I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!', + actions: ['REMOTE_ATTESTATION'], + }, + }, + ], + [ + { + name: '{{name1}}', + content: { + text: "It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'", + }, + }, + { + name: '{{agentName}}', + content: { + text: 'Oh, dear...lemme find that for you', + actions: ['REMOTE_ATTESTATION'], + }, + }, + ], + ], +}; diff --git a/src/index.ts b/src/index.ts index 09880da..c152d35 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,29 +1,66 @@ -import type { Plugin } from "@elizaos/core"; -import { remoteAttestationProvider } from "./providers/remoteAttestationProvider"; -import { deriveKeyProvider } from "./providers/deriveKeyProvider"; -import { remoteAttestationAction } from "./actions/remoteAttestation"; +import { + type IAgentRuntime, + type Plugin, + type TeePluginConfig, + type TeeVendorConfig, + logger, +} from '@elizaos/core'; +import { TeeVendorNames } from './vendors/types'; +import { getVendor } from './vendors/index'; -export { DeriveKeyProvider } from "./providers/deriveKeyProvider"; -export { RemoteAttestationProvider } from "./providers/remoteAttestationProvider"; -export { RemoteAttestationQuote, TEEMode } from "./types/tee"; +export { phalaRemoteAttestationAction } from './actions/remoteAttestationAction'; +export { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider'; +export { PhalaRemoteAttestationProvider } from './providers/remoteAttestationProvider'; +export type { TeeVendorConfig }; -export const teePlugin: Plugin = { - name: "tee", - description: - "TEE plugin with actions to generate remote attestations and derive keys", - actions: [ - /* custom actions */ - remoteAttestationAction, - ], - evaluators: [ - /* custom evaluators */ - ], - providers: [ - /* custom providers */ - remoteAttestationProvider, - deriveKeyProvider, - ], - services: [ - /* custom services */ - ], +/** + * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings. + * @param {Record} config - The configuration object containing TEE vendor information. + * @param {IAgentRuntime} runtime - The runtime object with TEE related settings. + * @returns {Promise} - A promise that resolves once the TEE is initialized. + */ +async function initializeTEE(config: Record, runtime: IAgentRuntime) { + if (config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR')) { + const vendor = config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR'); + logger.info(`Initializing TEE with vendor: ${vendor}`); + let plugin: Plugin; + switch (vendor) { + case 'phala': + plugin = teePlugin({ + vendor: TeeVendorNames.PHALA, + }); + break; + default: + throw new Error(`Invalid TEE vendor: ${vendor}`); + } + logger.info(`Pushing plugin: ${plugin.name}`); + runtime.plugins.push(plugin); + } +} + +/** + * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration. + * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin. + * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services. + */ +export const teePlugin = (config?: TeePluginConfig): Plugin => { + const vendorType = config?.vendor || TeeVendorNames.PHALA; + const vendor = getVendor(vendorType); + return { + name: vendor.getName(), + init: async (config: Record, runtime: IAgentRuntime) => { + return await initializeTEE( + { + ...config, + vendor: vendorType, + }, + runtime + ); + }, + description: vendor.getDescription(), + actions: vendor.getActions(), + evaluators: [], + providers: vendor.getProviders(), + services: [], + }; }; diff --git a/src/providers/base.ts b/src/providers/base.ts new file mode 100644 index 0000000..cf85fd6 --- /dev/null +++ b/src/providers/base.ts @@ -0,0 +1,36 @@ +import type { RemoteAttestationQuote } from '@elizaos/core'; +import type { TdxQuoteHashAlgorithms } from '@phala/dstack-sdk'; + +/** + * Abstract class for deriving keys from the TEE. + * You can implement your own logic for deriving keys from the TEE. + * @example + * ```ts + * class MyDeriveKeyProvider extends DeriveKeyProvider { + * private client: TappdClient; + * + * constructor(endpoint: string) { + * super(); + * this.client = new TappdClient(); + * } + * + * async rawDeriveKey(path: string, subject: string): Promise { + * return this.client.deriveKey(path, subject); + * } + * } + * ``` + */ +/** + * Abstract class representing a key provider for deriving keys. + */ +export abstract class DeriveKeyProvider {} + +/** + * Abstract class for remote attestation provider. + */ +export abstract class RemoteAttestationProvider { + abstract generateAttestation( + reportData: string, + hashAlgorithm?: TdxQuoteHashAlgorithms + ): Promise; +} diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index 8c533ad..56353e8 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -1,228 +1,234 @@ -import { - type IAgentRuntime, - type Memory, - type Provider, - type State, - elizaLogger, -} from "@elizaos/core"; -import { Keypair } from "@solana/web3.js"; -import crypto from "crypto"; -import { type DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; -import { privateKeyToAccount } from "viem/accounts"; -import { type PrivateKeyAccount, keccak256 } from "viem"; -import { RemoteAttestationProvider } from "./remoteAttestationProvider"; -import { TEEMode, type RemoteAttestationQuote, type DeriveKeyAttestationData } from "../types/tee"; - -class DeriveKeyProvider { - private client: TappdClient; - private raProvider: RemoteAttestationProvider; - - constructor(teeMode?: string) { - let endpoint: string | undefined; - - // Both LOCAL and DOCKER modes use the simulator, just with different endpoints - switch (teeMode) { - case TEEMode.LOCAL: - endpoint = "http://localhost:8090"; - elizaLogger.log( - "TEE: Connecting to local simulator at localhost:8090" - ); - break; - case TEEMode.DOCKER: - endpoint = "http://host.docker.internal:8090"; - elizaLogger.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); - break; - case TEEMode.PRODUCTION: - endpoint = undefined; - elizaLogger.log( - "TEE: Running in production mode without simulator" - ); - break; - default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); - } - - this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); - this.raProvider = new RemoteAttestationProvider(teeMode); +import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core'; +import { type DeriveKeyAttestationData, type RemoteAttestationQuote, TEEMode } from '@elizaos/core'; +import { type DeriveKeyResponse, TappdClient } from '@phala/dstack-sdk'; +import { Keypair } from '@solana/web3.js'; +import { toViemAccount } from '@phala/dstack-sdk/viem'; +import { toKeypair } from '@phala/dstack-sdk/solana'; +import { DeriveKeyProvider } from './base'; +import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from './remoteAttestationProvider'; + +/** + * Phala TEE Cloud Provider + * @example + * ```ts + * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE')); + * ``` + */ +/** + * A class representing a key provider for deriving keys in the Phala TEE environment. + * Extends the DeriveKeyProvider class. + */ +class PhalaDeriveKeyProvider extends DeriveKeyProvider { + private client: TappdClient; + private raProvider: RemoteAttestationProvider; + + constructor(teeMode?: string) { + super(); + let endpoint: string | undefined; + + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = 'http://localhost:8090'; + logger.log('TEE: Connecting to local simulator at localhost:8090'); + break; + case TEEMode.DOCKER: + endpoint = 'http://host.docker.internal:8090'; + logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090'); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + logger.log('TEE: Running in production mode without simulator'); + break; + default: + throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); } - private async generateDeriveKeyAttestation( - agentId: string, - publicKey: string, - subject?: string - ): Promise { - const deriveKeyData: DeriveKeyAttestationData = { - agentId, - publicKey, - subject, - }; - const reportdata = JSON.stringify(deriveKeyData); - elizaLogger.log( - "Generating Remote Attestation Quote for Derive Key..." - ); - const quote = await this.raProvider.generateAttestation(reportdata); - elizaLogger.log("Remote Attestation Quote generated successfully!"); - return quote; + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + this.raProvider = new RemoteAttestationProvider(teeMode); + } + + private async generateDeriveKeyAttestation( + agentId: string, + publicKey: string, + subject?: string + ): Promise { + const deriveKeyData: DeriveKeyAttestationData = { + agentId, + publicKey, + subject, + }; + const reportdata = JSON.stringify(deriveKeyData); + logger.log('Generating Remote Attestation Quote for Derive Key...'); + const quote = await this.raProvider.generateAttestation(reportdata); + logger.log('Remote Attestation Quote generated successfully!'); + return quote; + } + + /** + * Derives a raw key from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @returns The derived key. + */ + async rawDeriveKey(path: string, subject: string): Promise { + try { + if (!path || !subject) { + logger.error('Path and Subject are required for key derivation'); + } + + logger.log('Deriving Raw Key in TEE...'); + const derivedKey = await this.client.deriveKey(path, subject); + + logger.log('Raw Key Derived Successfully!'); + return derivedKey; + } catch (error) { + logger.error('Error deriving raw key:', error); + throw error; } - - /** - * Derives a raw key from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @returns The derived key. - */ - async rawDeriveKey( - path: string, - subject: string - ): Promise { - try { - if (!path || !subject) { - elizaLogger.error( - "Path and Subject are required for key derivation" - ); - } - - elizaLogger.log("Deriving Raw Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); - - elizaLogger.log("Raw Key Derived Successfully!"); - return derivedKey; - } catch (error) { - elizaLogger.error("Error deriving raw key:", error); - throw error; - } + } + + /** + * Derives an Ed25519 keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. + * @returns An object containing the derived keypair and attestation. + */ + async deriveEd25519Keypair( + path: string, + subject: string, + agentId: string + ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { + try { + if (!path || !subject) { + logger.error('Path and Subject are required for key derivation'); + } + + logger.log('Deriving Key in TEE...'); + const derivedKey = await this.client.deriveKey(path, subject); + const keypair = toKeypair(derivedKey); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.publicKey.toBase58() + ); + logger.log('Key Derived Successfully!'); + + return { keypair, attestation }; + } catch (error) { + logger.error('Error deriving key:', error); + throw error; } - - /** - * Derives an Ed25519 keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. - * @returns An object containing the derived keypair and attestation. - */ - async deriveEd25519Keypair( - path: string, - subject: string, - agentId: string - ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { - try { - if (!path || !subject) { - elizaLogger.error( - "Path and Subject are required for key derivation" - ); - } - - elizaLogger.log("Deriving Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); - const uint8ArrayDerivedKey = derivedKey.asUint8Array(); - - const hash = crypto.createHash("sha256"); - hash.update(uint8ArrayDerivedKey); - const seed = hash.digest(); - const seedArray = new Uint8Array(seed); - const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); - - // Generate an attestation for the derived key data for public to verify - const attestation = await this.generateDeriveKeyAttestation( - agentId, - keypair.publicKey.toBase58() - ); - elizaLogger.log("Key Derived Successfully!"); - - return { keypair, attestation }; - } catch (error) { - elizaLogger.error("Error deriving key:", error); - throw error; - } + } + + /** + * Derives an ECDSA keypair from the given path and subject. + * @param path - The path to derive the key from. This is used to derive the key from the root of trust. + * @param subject - The subject to derive the key from. This is used for the certificate chain. + * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. + * @returns An object containing the derived keypair and attestation. + */ + async deriveEcdsaKeypair( + path: string, + subject: string, + agentId: string + ): Promise<{ + keypair: PrivateKeyAccount; + attestation: RemoteAttestationQuote; + }> { + try { + if (!path || !subject) { + logger.error('Path and Subject are required for key derivation'); + } + + logger.log('Deriving ECDSA Key in TEE...'); + const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(path, subject); + const keypair = toViemAccount(deriveKeyResponse); + + // Generate an attestation for the derived key data for public to verify + const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address); + logger.log('ECDSA Key Derived Successfully!'); + + return { keypair, attestation }; + } catch (error) { + logger.error('Error deriving ecdsa key:', error); + throw error; } + } +} - /** - * Derives an ECDSA keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. - * @returns An object containing the derived keypair and attestation. - */ - async deriveEcdsaKeypair( - path: string, - subject: string, - agentId: string - ): Promise<{ - keypair: PrivateKeyAccount; - attestation: RemoteAttestationQuote; - }> { - try { - if (!path || !subject) { - elizaLogger.error( - "Path and Subject are required for key derivation" - ); - } - - elizaLogger.log("Deriving ECDSA Key in TEE..."); - const deriveKeyResponse: DeriveKeyResponse = - await this.client.deriveKey(path, subject); - const hex = keccak256(deriveKeyResponse.asUint8Array()); - const keypair: PrivateKeyAccount = privateKeyToAccount(hex); - - // Generate an attestation for the derived key data for public to verify - const attestation = await this.generateDeriveKeyAttestation( - agentId, - keypair.address - ); - elizaLogger.log("ECDSA Key Derived Successfully!"); - - return { keypair, attestation }; - } catch (error) { - elizaLogger.error("Error deriving ecdsa key:", error); - throw error; - } - } +// Define the ProviderResult interface if not already imported +interface ProviderResult { + data?: any; + values?: Record; + text?: string; } -const deriveKeyProvider: Provider = { - get: async (runtime: IAgentRuntime, _message?: Memory, _state?: State) => { - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new DeriveKeyProvider(teeMode); - const agentId = runtime.agentId; - try { - // Validate wallet configuration - if (!runtime.getSetting("WALLET_SECRET_SALT")) { - elizaLogger.error( - "Wallet secret salt is not configured in settings" - ); - return ""; - } - - try { - const secretSalt = - runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; - const solanaKeypair = await provider.deriveEd25519Keypair( - secretSalt, - "solana", - agentId - ); - const evmKeypair = await provider.deriveEcdsaKeypair( - secretSalt, - "evm", - agentId - ); - return JSON.stringify({ - solana: solanaKeypair.keypair.publicKey, - evm: evmKeypair.keypair.address, - }); - } catch (error) { - elizaLogger.error("Error creating PublicKey:", error); - return ""; - } - } catch (error) { - elizaLogger.error("Error in derive key provider:", error.message); - return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`; - } - }, +const phalaDeriveKeyProvider: Provider = { + name: 'phala-derive-key', + get: async (runtime: IAgentRuntime, _message?: Memory): Promise => { + const teeMode = runtime.getSetting('TEE_MODE'); + const provider = new PhalaDeriveKeyProvider(teeMode); + const agentId = runtime.agentId; + try { + // Validate wallet configuration + if (!runtime.getSetting('WALLET_SECRET_SALT')) { + logger.error('Wallet secret salt is not configured in settings'); + return { + data: null, + values: {}, + text: 'Wallet secret salt is not configured in settings', + }; + } + + try { + const secretSalt = runtime.getSetting('WALLET_SECRET_SALT') || 'secret_salt'; + const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, 'solana', agentId); + const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, 'evm', agentId); + + // Original data structure + const walletData = { + solana: solanaKeypair.keypair.publicKey, + evm: evmKeypair.keypair.address, + }; + + // Values for template injection + const values = { + solana_public_key: solanaKeypair.keypair.publicKey.toString(), + evm_address: evmKeypair.keypair.address, + }; + + // Text representation + const text = `Solana Public Key: ${values.solana_public_key}\nEVM Address: ${values.evm_address}`; + + return { + data: walletData, + values: values, + text: text, + }; + } catch (error) { + logger.error('Error creating PublicKey:', error); + return { + data: null, + values: {}, + text: `Error creating PublicKey: ${ + error instanceof Error ? error.message : 'Unknown error' + }`, + }; + } + } catch (error) { + logger.error('Error in derive key provider:', error.message); + return { + data: null, + values: {}, + text: `Failed to fetch derive key information: ${ + error instanceof Error ? error.message : 'Unknown error' + }`, + }; + } + }, }; -export { deriveKeyProvider, DeriveKeyProvider }; +export { phalaDeriveKeyProvider, PhalaDeriveKeyProvider }; diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts index 478ff26..46c8246 100644 --- a/src/providers/remoteAttestationProvider.ts +++ b/src/providers/remoteAttestationProvider.ts @@ -1,106 +1,122 @@ -import { - type IAgentRuntime, - type Memory, - type Provider, - type State, - elizaLogger, -} from "@elizaos/core"; -import { type TdxQuoteResponse, TappdClient, type TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; -import { type RemoteAttestationQuote, TEEMode, type RemoteAttestationMessage } from "../types/tee"; +import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core'; +import { type RemoteAttestationMessage, type RemoteAttestationQuote, TEEMode } from '@elizaos/core'; +import { TappdClient, type TdxQuoteHashAlgorithms, type TdxQuoteResponse } from '@phala/dstack-sdk'; +import { RemoteAttestationProvider } from './base'; -class RemoteAttestationProvider { - private client: TappdClient; +// Define the ProviderResult interface if not already imported +/** + * Interface for the result returned by a provider. + * @typedef {Object} ProviderResult + * @property {any} data - The data returned by the provider. + * @property {Record} values - The values returned by the provider. + * @property {string} text - The text returned by the provider. + */ +interface ProviderResult { + data?: any; + values?: Record; + text?: string; +} - constructor(teeMode?: string) { - let endpoint: string | undefined; +/** + * Phala TEE Cloud Provider + * @example + * ```ts + * const provider = new PhalaRemoteAttestationProvider(); + * ``` + */ +/** + * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider + * @extends RemoteAttestationProvider + */ +class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { + private client: TappdClient; - // Both LOCAL and DOCKER modes use the simulator, just with different endpoints - switch (teeMode) { - case TEEMode.LOCAL: - endpoint = "http://localhost:8090"; - elizaLogger.log( - "TEE: Connecting to local simulator at localhost:8090" - ); - break; - case TEEMode.DOCKER: - endpoint = "http://host.docker.internal:8090"; - elizaLogger.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); - break; - case TEEMode.PRODUCTION: - endpoint = undefined; - elizaLogger.log( - "TEE: Running in production mode without simulator" - ); - break; - default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); - } + constructor(teeMode?: string) { + super(); + let endpoint: string | undefined; - this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + // Both LOCAL and DOCKER modes use the simulator, just with different endpoints + switch (teeMode) { + case TEEMode.LOCAL: + endpoint = 'http://localhost:8090'; + logger.log('TEE: Connecting to local simulator at localhost:8090'); + break; + case TEEMode.DOCKER: + endpoint = 'http://host.docker.internal:8090'; + logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090'); + break; + case TEEMode.PRODUCTION: + endpoint = undefined; + logger.log('TEE: Running in production mode without simulator'); + break; + default: + throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); } - async generateAttestation( - reportData: string, - hashAlgorithm?: TdxQuoteHashAlgorithms - ): Promise { - try { - elizaLogger.log("Generating attestation for: ", reportData); - const tdxQuote: TdxQuoteResponse = - await this.client.tdxQuote(reportData, hashAlgorithm); - const rtmrs = tdxQuote.replayRtmrs(); - elizaLogger.log( - `rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f` - ); - const quote: RemoteAttestationQuote = { - quote: tdxQuote.quote, - timestamp: Date.now(), - }; - elizaLogger.log("Remote attestation quote: ", quote); - return quote; - } catch (error) { - console.error("Error generating remote attestation:", error); - throw new Error( - `Failed to generate TDX Quote: ${ - error instanceof Error ? error.message : "Unknown error" - }` - ); - } + this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + } + + async generateAttestation( + reportData: string, + hashAlgorithm?: TdxQuoteHashAlgorithms + ): Promise { + try { + logger.log('Generating attestation for: ', reportData); + const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(reportData, hashAlgorithm); + const rtmrs = tdxQuote.replayRtmrs(); + logger.log(`rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f`); + const quote: RemoteAttestationQuote = { + quote: tdxQuote.quote, + timestamp: Date.now(), + }; + logger.log('Remote attestation quote: ', quote); + return quote; + } catch (error) { + console.error('Error generating remote attestation:', error); + throw new Error( + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}` + ); } + } } // Keep the original provider for backwards compatibility -const remoteAttestationProvider: Provider = { - get: async (runtime: IAgentRuntime, message: Memory, _state?: State) => { - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new RemoteAttestationProvider(teeMode); - const agentId = runtime.agentId; +const phalaRemoteAttestationProvider: Provider = { + name: 'phala-remote-attestation', + get: async (runtime: IAgentRuntime, message: Memory) => { + const teeMode = runtime.getSetting('TEE_MODE'); + const provider = new PhalaRemoteAttestationProvider(teeMode); + const agentId = runtime.agentId; - try { - const attestationMessage: RemoteAttestationMessage = { - agentId: agentId, - timestamp: Date.now(), - message: { - userId: message.userId, - roomId: message.roomId, - content: message.content.text, - } - }; - elizaLogger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); - return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`; - } catch (error) { - console.error("Error in remote attestation provider:", error); - throw new Error( - `Failed to generate TDX Quote: ${ - error instanceof Error ? error.message : "Unknown error" - }` - ); - } - }, + try { + const attestationMessage: RemoteAttestationMessage = { + agentId: agentId, + timestamp: Date.now(), + message: { + entityId: message.entityId, + roomId: message.roomId, + content: message.content.text, + }, + }; + logger.log('Generating attestation for: ', JSON.stringify(attestationMessage)); + const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + return { + text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`, + data: { + attestation, + }, + values: { + quote: attestation.quote, + timestamp: attestation.timestamp.toString(), + }, + }; + } catch (error) { + console.error('Error in remote attestation provider:', error); + throw new Error( + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } + }, }; -export { remoteAttestationProvider, RemoteAttestationProvider }; +export { phalaRemoteAttestationProvider, PhalaRemoteAttestationProvider }; diff --git a/src/providers/walletProvider.ts b/src/providers/walletProvider.ts deleted file mode 100644 index 5177a7d..0000000 --- a/src/providers/walletProvider.ts +++ /dev/null @@ -1,326 +0,0 @@ -/* This is an example of how WalletProvider can use DeriveKeyProvider to generate a Solana Keypair */ -import { - type IAgentRuntime, - type Memory, - type Provider, - type State, - elizaLogger, -} from "@elizaos/core"; -import { Connection, type Keypair, type PublicKey } from "@solana/web3.js"; -import BigNumber from "bignumber.js"; -import NodeCache from "node-cache"; -import { DeriveKeyProvider } from "./deriveKeyProvider"; -import type { RemoteAttestationQuote } from "../types/tee"; -// Provider configuration -const PROVIDER_CONFIG = { - BIRDEYE_API: "https://public-api.birdeye.so", - MAX_RETRIES: 3, - RETRY_DELAY: 2000, - DEFAULT_RPC: "https://api.mainnet-beta.solana.com", - TOKEN_ADDRESSES: { - SOL: "So11111111111111111111111111111111111111112", - BTC: "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh", - ETH: "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs", - }, -}; - -export interface Item { - name: string; - address: string; - symbol: string; - decimals: number; - balance: string; - uiAmount: string; - priceUsd: string; - valueUsd: string; - valueSol?: string; -} - -interface WalletPortfolio { - totalUsd: string; - totalSol?: string; - items: Array; -} - -interface _BirdEyePriceData { - data: { - [key: string]: { - price: number; - priceChange24h: number; - }; - }; -} - -interface Prices { - solana: { usd: string }; - bitcoin: { usd: string }; - ethereum: { usd: string }; -} - -export class WalletProvider { - private cache: NodeCache; - - constructor( - private connection: Connection, - private walletPublicKey: PublicKey - ) { - this.cache = new NodeCache({ stdTTL: 300 }); // Cache TTL set to 5 minutes - } - - private async fetchWithRetry( - runtime, - url: string, - options: RequestInit = {} - ): Promise { - let lastError: Error; - - for (let i = 0; i < PROVIDER_CONFIG.MAX_RETRIES; i++) { - try { - const apiKey = runtime.getSetting("BIRDEYE_API_KEY"); - const response = await fetch(url, { - ...options, - headers: { - Accept: "application/json", - "x-chain": "solana", - "X-API-KEY": apiKey || "", - ...options.headers, - }, - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `HTTP error! status: ${response.status}, message: ${errorText}` - ); - } - - const data = await response.json(); - return data; - } catch (error) { - elizaLogger.error(`Attempt ${i + 1} failed:`, error); - lastError = error; - if (i < PROVIDER_CONFIG.MAX_RETRIES - 1) { - const delay = PROVIDER_CONFIG.RETRY_DELAY * Math.pow(2, i); - await new Promise((resolve) => setTimeout(resolve, delay)); - continue; - } - } - } - - elizaLogger.error( - "All attempts failed. Throwing the last error:", - lastError - ); - throw lastError; - } - - async fetchPortfolioValue(runtime): Promise { - try { - const cacheKey = `portfolio-${this.walletPublicKey.toBase58()}`; - const cachedValue = this.cache.get(cacheKey); - - if (cachedValue) { - elizaLogger.log("Cache hit for fetchPortfolioValue"); - return cachedValue; - } - elizaLogger.log("Cache miss for fetchPortfolioValue"); - - const walletData = await this.fetchWithRetry( - runtime, - `${PROVIDER_CONFIG.BIRDEYE_API}/v1/wallet/token_list?wallet=${this.walletPublicKey.toBase58()}` - ); - - if (!walletData?.success || !walletData?.data) { - elizaLogger.error("No portfolio data available", walletData); - throw new Error("No portfolio data available"); - } - - const data = walletData.data; - const totalUsd = new BigNumber(data.totalUsd.toString()); - const prices = await this.fetchPrices(runtime); - const solPriceInUSD = new BigNumber(prices.solana.usd.toString()); - - const items = data.items.map((item: any) => ({ - ...item, - valueSol: new BigNumber(item.valueUsd || 0) - .div(solPriceInUSD) - .toFixed(6), - name: item.name || "Unknown", - symbol: item.symbol || "Unknown", - priceUsd: item.priceUsd || "0", - valueUsd: item.valueUsd || "0", - })); - - const totalSol = totalUsd.div(solPriceInUSD); - const portfolio = { - totalUsd: totalUsd.toString(), - totalSol: totalSol.toFixed(6), - items: items.sort((a, b) => - new BigNumber(b.valueUsd) - .minus(new BigNumber(a.valueUsd)) - .toNumber() - ), - }; - this.cache.set(cacheKey, portfolio); - return portfolio; - } catch (error) { - elizaLogger.error("Error fetching portfolio:", error); - throw error; - } - } - - async fetchPrices(runtime): Promise { - try { - const cacheKey = "prices"; - const cachedValue = this.cache.get(cacheKey); - - if (cachedValue) { - elizaLogger.log("Cache hit for fetchPrices"); - return cachedValue; - } - elizaLogger.log("Cache miss for fetchPrices"); - - const { SOL, BTC, ETH } = PROVIDER_CONFIG.TOKEN_ADDRESSES; - const tokens = [SOL, BTC, ETH]; - const prices: Prices = { - solana: { usd: "0" }, - bitcoin: { usd: "0" }, - ethereum: { usd: "0" }, - }; - - for (const token of tokens) { - const response = await this.fetchWithRetry( - runtime, - `${PROVIDER_CONFIG.BIRDEYE_API}/defi/price?address=${token}`, - { - headers: { - "x-chain": "solana", - }, - } - ); - - if (response?.data?.value) { - const price = response.data.value.toString(); - prices[ - token === SOL - ? "solana" - : token === BTC - ? "bitcoin" - : "ethereum" - ].usd = price; - } else { - elizaLogger.warn( - `No price data available for token: ${token}` - ); - } - } - - this.cache.set(cacheKey, prices); - return prices; - } catch (error) { - elizaLogger.error("Error fetching prices:", error); - throw error; - } - } - - formatPortfolio( - runtime, - portfolio: WalletPortfolio, - prices: Prices - ): string { - let output = `${runtime.character.description}\n`; - output += `Wallet Address: ${this.walletPublicKey.toBase58()}\n\n`; - - const totalUsdFormatted = new BigNumber(portfolio.totalUsd).toFixed(2); - const totalSolFormatted = portfolio.totalSol; - - output += `Total Value: $${totalUsdFormatted} (${totalSolFormatted} SOL)\n\n`; - output += "Token Balances:\n"; - - const nonZeroItems = portfolio.items.filter((item) => - new BigNumber(item.uiAmount).isGreaterThan(0) - ); - - if (nonZeroItems.length === 0) { - output += "No tokens found with non-zero balance\n"; - } else { - for (const item of nonZeroItems) { - const valueUsd = new BigNumber(item.valueUsd).toFixed(2); - output += `${item.name} (${item.symbol}): ${new BigNumber( - item.uiAmount - ).toFixed(6)} ($${valueUsd} | ${item.valueSol} SOL)\n`; - } - } - - output += "\nMarket Prices:\n"; - output += `SOL: $${new BigNumber(prices.solana.usd).toFixed(2)}\n`; - output += `BTC: $${new BigNumber(prices.bitcoin.usd).toFixed(2)}\n`; - output += `ETH: $${new BigNumber(prices.ethereum.usd).toFixed(2)}\n`; - - return output; - } - - async getFormattedPortfolio(runtime): Promise { - try { - const [portfolio, prices] = await Promise.all([ - this.fetchPortfolioValue(runtime), - this.fetchPrices(runtime), - ]); - - return this.formatPortfolio(runtime, portfolio, prices); - } catch (error) { - elizaLogger.error("Error generating portfolio report:", error); - return "Unable to fetch wallet information. Please try again later."; - } - } -} - -const walletProvider: Provider = { - get: async ( - runtime: IAgentRuntime, - _message: Memory, - _state?: State - ): Promise => { - const agentId = runtime.agentId; - const teeMode = runtime.getSetting("TEE_MODE"); - const deriveKeyProvider = new DeriveKeyProvider(teeMode); - try { - // Validate wallet configuration - if (!runtime.getSetting("WALLET_SECRET_SALT")) { - elizaLogger.error( - "Wallet secret salt is not configured in settings" - ); - return ""; - } - - let publicKey: PublicKey; - try { - const derivedKeyPair: { - keypair: Keypair; - attestation: RemoteAttestationQuote; - } = await deriveKeyProvider.deriveEd25519Keypair( - runtime.getSetting("WALLET_SECRET_SALT"), - "solana", - agentId - ); - publicKey = derivedKeyPair.keypair.publicKey; - elizaLogger.log("Wallet Public Key: ", publicKey.toBase58()); - } catch (error) { - elizaLogger.error("Error creating PublicKey:", error); - return ""; - } - - const connection = new Connection(PROVIDER_CONFIG.DEFAULT_RPC); - const provider = new WalletProvider(connection, publicKey); - - const porfolio = await provider.getFormattedPortfolio(runtime); - return porfolio; - } catch (error) { - elizaLogger.error("Error in wallet provider:", error.message); - return `Failed to fetch wallet information: ${error instanceof Error ? error.message : "Unknown error"}`; - } - }, -}; - -// Module exports -export { walletProvider }; diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..6a85619 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,10 @@ +/** + * Enum representing different types of Tee. + * @enum {string} + * @readonly + */ + +export enum TeeType { + SGX_GRAMINE = 'sgx_gramine', + TDX_DSTACK = 'tdx_dstack', +} \ No newline at end of file diff --git a/src/types/tee.ts b/src/types/tee.ts deleted file mode 100644 index 9e3ae1f..0000000 --- a/src/types/tee.ts +++ /dev/null @@ -1,27 +0,0 @@ -export enum TEEMode { - OFF = "OFF", - LOCAL = "LOCAL", // For local development with simulator - DOCKER = "DOCKER", // For docker development with simulator - PRODUCTION = "PRODUCTION", // For production without simulator -} - -export interface RemoteAttestationQuote { - quote: string; - timestamp: number; -} - -export interface DeriveKeyAttestationData { - agentId: string; - publicKey: string; - subject?: string; -} - -export interface RemoteAttestationMessage { - agentId: string; - timestamp: number; - message: { - userId: string; - roomId: string; - content: string; - } -} \ No newline at end of file diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..c2f6fbe --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,41 @@ +import { createHash } from 'node:crypto'; + +/** + * Converts a hexadecimal string to a Uint8Array. + * + * @param {string} hex - The hexadecimal string to convert. + * @returns {Uint8Array} - The resulting Uint8Array. + * @throws {Error} - If the input hex string is invalid. + */ +export function hexToUint8Array(hex: string) { + const hexString = hex.trim().replace(/^0x/, ''); + if (!hexString) { + throw new Error('Invalid hex string'); + } + if (hexString.length % 2 !== 0) { + throw new Error('Invalid hex string'); + } + + const array = new Uint8Array(hexString.length / 2); + for (let i = 0; i < hexString.length; i += 2) { + const byte = Number.parseInt(hexString.slice(i, i + 2), 16); + if (Number.isNaN(byte)) { + throw new Error('Invalid hex string'); + } + array[i / 2] = byte; + } + return array; +} + +// Function to calculate SHA-256 and return a Buffer (32 bytes) +/** + * Calculates the SHA256 hash of the input string. + * + * @param {string} input - The input string to calculate the hash from. + * @returns {Buffer} - The calculated SHA256 hash as a Buffer object. + */ +export function calculateSHA256(input: string): Buffer { + const hash = createHash('sha256'); + hash.update(input); + return hash.digest(); +} diff --git a/src/vendors/index.ts b/src/vendors/index.ts new file mode 100644 index 0000000..6cd82ba --- /dev/null +++ b/src/vendors/index.ts @@ -0,0 +1,17 @@ +import { PhalaVendor } from './phala'; +import type { TeeVendor } from './types'; +import { type TeeVendorName, TeeVendorNames } from './types'; + +const vendors: Record = { + [TeeVendorNames.PHALA]: new PhalaVendor(), +}; + +export const getVendor = (type: TeeVendorName): TeeVendor => { + const vendor = vendors[type]; + if (!vendor) { + throw new Error(`Unsupported TEE vendor type: ${type}`); + } + return vendor; +}; + +export * from './types'; diff --git a/src/vendors/phala.ts b/src/vendors/phala.ts new file mode 100644 index 0000000..970a728 --- /dev/null +++ b/src/vendors/phala.ts @@ -0,0 +1,58 @@ +import { phalaRemoteAttestationAction as remoteAttestationAction } from '../actions/remoteAttestationAction'; +import { phalaDeriveKeyProvider as deriveKeyProvider } from '../providers/deriveKeyProvider'; +import { phalaRemoteAttestationProvider as remoteAttestationProvider } from '../providers/remoteAttestationProvider'; +import { type TeeVendor, TeeVendorNames } from './types'; + +/** + * A class representing a vendor for Phala TEE. + * * @implements { TeeVendor } + * @type {TeeVendorNames.PHALA} + *//** + * Get the actions for the PhalaVendor. + * * @returns { Array } An array of actions. + *//** + * Get the providers for the PhalaVendor. + * * @returns { Array } An array of providers. + *//** + * Get the name of the PhalaVendor. + * * @returns { string } The name of the vendor. + *//** + * Get the description of the PhalaVendor. + * * @returns { string } The description of the vendor. + */ +export class PhalaVendor implements TeeVendor { + type = TeeVendorNames.PHALA; + + /** + * Returns an array of actions. + * + * @returns {Array} An array containing the remote attestation action. + */ + getActions() { + return [remoteAttestationAction]; + } + /** + * Retrieve the list of providers. + * + * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider. + */ + getProviders() { + return [deriveKeyProvider, remoteAttestationProvider]; + } + + /** + * Returns the name of the plugin. + * @returns {string} The name of the plugin. + */ + getName() { + return 'phala-tee-plugin'; + } + + /** + * Get the description of the function + * @returns {string} The description of the function + */ + getDescription() { + return 'Phala TEE Cloud to Host Eliza Agents'; + } +} diff --git a/src/vendors/types.ts b/src/vendors/types.ts new file mode 100644 index 0000000..2cb9c8b --- /dev/null +++ b/src/vendors/types.ts @@ -0,0 +1,24 @@ +import type { Action, Provider } from '@elizaos/core'; + +export const TeeVendorNames = { + PHALA: 'phala', +} as const; + +/** + * Type representing the name of a Tee vendor. + * It can either be one of the keys of TeeVendorNames or a string. + */ +export type TeeVendorName = (typeof TeeVendorNames)[keyof typeof TeeVendorNames] | string; + +/** + * Interface for a TeeVendor, representing a vendor that sells tees. + * @interface + */ + +export interface TeeVendor { + type: TeeVendorName; + getActions(): Action[]; + getProviders(): Provider[]; + getName(): string; + getDescription(): string; +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..625391d --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "outDir": "./dist", + "sourceMap": true, + "inlineSources": true, + "declaration": true, + "emitDeclarationOnly": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"] +} diff --git a/tsconfig.json b/tsconfig.json index 005fbac..e168e2b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,8 +1,15 @@ { - "extends": "../core/tsconfig.json", - "compilerOptions": { - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src/**/*.ts"] + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "module": "ESNext", + "target": "ESNext", + "types": ["node"], + "baseUrl": ".", + "paths": { + "@elizaos/core": ["../core/src"], + "@elizaos/core/*": ["../core/src/*"] + } + }, + "include": ["src/**/*.ts"] } diff --git a/tsup.config.ts b/tsup.config.ts index f6f7876..b91996a 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,30 +1,31 @@ -import { defineConfig } from "tsup"; +import { defineConfig } from 'tsup'; export default defineConfig({ - entry: ["src/index.ts"], - outDir: "dist", - sourcemap: true, - clean: true, - format: ["esm"], // Ensure you're targeting CommonJS - external: [ - "@elizaos/core", - "dotenv", // Externalize dotenv to prevent bundling - "fs", // Externalize fs to use Node.js built-in module - "path", // Externalize other built-ins if necessary - "@reflink/reflink", - "@node-llama-cpp", - "https", - "http", - "agentkeepalive", - // Add other modules you want to externalize - "@phala/dstack-sdk", - "safe-buffer", - "base-x", - "bs58", - "borsh", - "@solana/buffer-layout", - "stream", - "buffer", - "undici", - ], + entry: ['src/index.ts'], + outDir: 'dist', + tsconfig: './tsconfig.build.json', // Use build-specific tsconfig + sourcemap: true, + format: ['esm'], // Ensure you're targeting CommonJS + dts: false, // Skip DTS generation to avoid external import issues // Ensure you're targeting CommonJS + external: [ + 'dotenv', // Externalize dotenv to prevent bundling + 'fs', // Externalize fs to use Node.js built-in module + 'path', // Externalize other built-ins if necessary + '@reflink/reflink', + '@node-llama-cpp', + 'https', + 'http', + 'agentkeepalive', + 'safe-buffer', + 'base-x', + 'bs58', + 'borsh', + 'stream', + 'buffer', + // Add other modules you want to externalize + '@phala/dstack-sdk', + 'undici', + '@elizaos/core', + 'zod', + ], }); From d286439f3d221e495b256246581feaae99001cdc Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Thu, 15 May 2025 17:28:31 -0500 Subject: [PATCH 16/39] update to latest --- .gitignore | 6 +++++- package.json | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index dfdbf1f..fdf2c2b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ node_modules .turbo -dist \ No newline at end of file +dist +elizaConfig.yaml +custom_actions/ +cache/ +*.tsbuildinfo \ No newline at end of file diff --git a/package.json b/package.json index c8fca7e..b44f305 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.49", + "version": "1.0.0-beta.51", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "dependencies": { - "@elizaos/core": "^1.0.0-beta.49", + "@elizaos/core": "^1.0.0-beta.51", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.0", "viem": "2.23.11" From 69aefdd0d068569f326b5a84d0b265f017375535 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Sat, 17 May 2025 17:24:06 -0600 Subject: [PATCH 17/39] deploy action, lint, tsconfig, deps, fix tests --- .github/workflows/npm-deploy.yml | 122 +++ bun.lock | 1018 ++++++++++++++++++++ bun.lockb | Bin 164895 -> 0 bytes dist/index.js | 102 +- dist/index.js.map | 2 +- package.json | 29 +- src/__tests__/deriveKey.test.ts | 100 +- src/__tests__/remoteAttestation.test.ts | 85 +- src/__tests__/timeout.test.ts | 157 +-- src/actions/remoteAttestationAction.ts | 85 +- src/index.ts | 23 +- src/providers/base.ts | 4 +- src/providers/deriveKeyProvider.ts | 135 ++- src/providers/remoteAttestationProvider.ts | 73 +- src/types.ts | 6 +- src/utils.ts | 12 +- src/vendors/index.ts | 10 +- src/vendors/phala.ts | 12 +- src/vendors/types.ts | 8 +- tsconfig.json | 15 +- tsup.config.ts | 2 +- 21 files changed, 1662 insertions(+), 338 deletions(-) create mode 100644 .github/workflows/npm-deploy.yml create mode 100644 bun.lock delete mode 100755 bun.lockb diff --git a/.github/workflows/npm-deploy.yml b/.github/workflows/npm-deploy.yml new file mode 100644 index 0000000..566a06d --- /dev/null +++ b/.github/workflows/npm-deploy.yml @@ -0,0 +1,122 @@ +name: Publish Package + +on: + push: + branches: + - 1.x + - 0.x + workflow_dispatch: + +jobs: + verify_version: + runs-on: ubuntu-latest + outputs: + should_publish: ${{ steps.check.outputs.should_publish }} + version: ${{ steps.check.outputs.version }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check if package.json version changed + id: check + run: | + echo "Current branch: ${{ github.ref }}" + + # Get current version + CURRENT_VERSION=$(jq -r .version package.json) + echo "Current version: $CURRENT_VERSION" + + # Get previous commit hash + git rev-parse HEAD~1 || git rev-parse HEAD + PREV_COMMIT=$(git rev-parse HEAD~1 2>/dev/null || git rev-parse HEAD) + + # Check if package.json changed + if git diff --name-only HEAD~1 HEAD | grep "package.json"; then + echo "Package.json was changed in this commit" + + # Get previous version if possible + if git show "$PREV_COMMIT:package.json" 2>/dev/null; then + PREV_VERSION=$(git show "$PREV_COMMIT:package.json" | jq -r .version) + echo "Previous version: $PREV_VERSION" + + if [ "$CURRENT_VERSION" != "$PREV_VERSION" ]; then + echo "Version changed from $PREV_VERSION to $CURRENT_VERSION" + echo "should_publish=true" >> $GITHUB_OUTPUT + else + echo "Version unchanged" + echo "should_publish=false" >> $GITHUB_OUTPUT + fi + else + echo "First commit with package.json, will publish" + echo "should_publish=true" >> $GITHUB_OUTPUT + fi + else + echo "Package.json not changed in this commit" + echo "should_publish=false" >> $GITHUB_OUTPUT + fi + + echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT + + publish: + needs: verify_version + if: needs.verify_version.outputs.should_publish == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Create Git tag + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -a "v${{ needs.verify_version.outputs.version }}" -m "Release v${{ needs.verify_version.outputs.version }}" + git push origin "v${{ needs.verify_version.outputs.version }}" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Build package + run: bun run build + + - name: Publish to npm + run: | + # strip “refs/heads/” prefix + BRANCH=${GITHUB_REF#refs/heads/} + if [[ "$BRANCH" == "1.x" ]]; then + echo "Publishing to npm under the 'beta' tag" + bun publish --tag beta + else + echo "Publishing to npm under the 'latest' tag" + bun publish + fi + env: + NPM_CONFIG_TOKEN: ${{ secrets.NPM_TOKEN }} + + create_release: + needs: [verify_version, publish] + if: needs.verify_version.outputs.should_publish == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Create GitHub Release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: "v${{ needs.verify_version.outputs.version }}" + release_name: "v${{ needs.verify_version.outputs.version }}" + body: "Release v${{ needs.verify_version.outputs.version }}" + draft: false + prerelease: false diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..6606b69 --- /dev/null +++ b/bun.lock @@ -0,0 +1,1018 @@ +{ + "lockfileVersion": 1, + "workspaces": { + "": { + "name": "@elizaos/plugin-tee", + "dependencies": { + "@elizaos/core": "^1.0.0-beta.51", + "@phala/dstack-sdk": "0.1.11", + "@solana/web3.js": "1.98.2", + "viem": "2.29.4", + "vitest": "^3.1.3", + }, + "devDependencies": { + "@types/node": "^22.15.3", + "prettier": "3.5.3", + "tsup": "8.5.0", + "typescript": "5.8.3", + }, + }, + }, + "packages": { + "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], + + "@babel/runtime": ["@babel/runtime@7.27.1", "", {}, "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog=="], + + "@cfworker/json-schema": ["@cfworker/json-schema@4.1.1", "", {}, "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og=="], + + "@elizaos/core": ["@elizaos/core@1.0.0-beta.52", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-trace-otlp-http": "^0.53.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/sdk-metrics": "^1.26.0", "@opentelemetry/sdk-node": "^0.53.0", "buffer": "^6.0.3", "crypto-browserify": "^3.12.1", "dotenv": "16.4.5", "events": "^3.3.0", "glob": "11.0.0", "handlebars": "^4.7.8", "js-sha1": "0.7.0", "langchain": "^0.3.15", "pino": "^9.6.0", "pino-pretty": "^13.0.0", "stream-browserify": "^3.0.0", "unique-names-generator": "4.7.1", "uuid": "11.0.3" } }, "sha512-A6YbJiKF3WbcAKQG6e3eC9sG8Dc1vTVUV1PZgJJFLErk2KuetTFSO3bs7OoNgvnTJfILd/8r44ig6kpPYe+FDA=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.4", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.25.4", "", { "os": "android", "cpu": "arm" }, "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.4", "", { "os": "android", "cpu": "arm64" }, "sha512-bBy69pgfhMGtCnwpC/x5QhfxAz/cBgQ9enbtwjf6V9lnPI/hMyT9iWpR1arm0l3kttTr4L0KSLpKmLp/ilKS9A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.25.4", "", { "os": "android", "cpu": "x64" }, "sha512-TVhdVtQIFuVpIIR282btcGC2oGQoSfZfmBdTip2anCaVYcqWlZXGcdcKIUklfX2wj0JklNYgz39OBqh2cqXvcQ=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Y1giCfM4nlHDWEfSckMzeWNdQS31BQGs9/rouw6Ub91tkK79aIMTH3q9xHvzH8d0wDru5Ci0kWB8b3up/nl16g=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-CJsry8ZGM5VFVeyUYB3cdKpd/H69PYez4eJh1W/t38vzutdjEjtP7hB6eLKBoOdxcAlCtEYHzQ/PJ/oU9I4u0A=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.4", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-yYq+39NlTRzU2XmoPW4l5Ifpl9fqSk0nAJYM/V/WUGPEFfek1epLHJIkTQM6bBs1swApjO5nWgvr843g6TjxuQ=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-0FgvOJ6UUMflsHSPLzdfDnnBBVoCDtBTVyn/MrWloUNvq/5SFmh13l3dvgRPkDihRxb77Y17MbqbCAa2strMQQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.4", "", { "os": "linux", "cpu": "arm" }, "sha512-kro4c0P85GMfFYqW4TWOpvmF8rFShbWGnrLqlzp4X1TNWjRY3JMYUfDCtOxPKOIY8B0WC8HN51hGP4I4hz4AaQ=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-+89UsQTfXdmjIvZS6nUnOOLoXnkUTB9hR5QAeLrQdzOSWZvNSAXAtcRDHWtqAUtAmv7ZM1WPOOeSxDzzzMogiQ=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.4", "", { "os": "linux", "cpu": "ia32" }, "sha512-yTEjoapy8UP3rv8dB0ip3AfMpRbyhSN3+hY8mo/i4QXFeDxmiYbEKp3ZRjBKcOP862Ua4b1PDfwlvbuwY7hIGQ=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-NeqqYkrcGzFwi6CGRGNMOjWGGSYOpqwCjS9fvaUlX5s3zwOtn1qwg1s2iE2svBe4Q/YOG1q6875lcAoQK/F4VA=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-IcvTlF9dtLrfL/M8WgNI/qJYBENP3ekgsHbYUIzEzq5XJzzVEV/fXY9WFPfEEXmu3ck2qJP8LG/p3Q8f7Zc2Xg=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-HOy0aLTJTVtoTeGZh4HSXaO6M95qu4k5lJcH4gxv56iaycfz1S8GO/5Jh6X4Y1YiI0h7cRyLi+HixMR+88swag=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-i8JUDAufpz9jOzo4yIShCTcXzS07vEgWzyX3NH2G7LEFVgrLEhjwL3ajFE4fZI3I4ZgiM7JH3GQ7ReObROvSUA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-jFnu+6UbLlzIjPQpWCNh5QtrcNfMLjgIavnwPQAfoGx4q17ocOU9MsQ2QVvFxwQoWpZT8DvTLooTvmOQXkO51g=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.4", "", { "os": "none", "cpu": "arm64" }, "sha512-vUnkBYxZW4hL/ie91hSqaSNjulOnYXE1VSLusnvHg2u3jewJBz3YzB9+oCw8DABeVqZGg94t9tyZFoHma8gWZQ=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.4", "", { "os": "none", "cpu": "x64" }, "sha512-XAg8pIQn5CzhOB8odIcAm42QsOfa98SBeKUdo4xa8OvX8LbMZqEtgeWE9P/Wxt7MlG2QqvjGths+nq48TrUiKw=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.4", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-Ct2WcFEANlFDtp1nVAXSNBPDxyU+j7+tId//iHXU2f/lN5AmO4zLyhDcpR5Cz1r08mVxzt3Jpyt4PmXQ1O6+7A=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.4", "", { "os": "openbsd", "cpu": "x64" }, "sha512-xAGGhyOQ9Otm1Xu8NT1ifGLnA6M3sJxZ6ixylb+vIUVzvvd6GOALpwQrYrtlPouMqd/vSbgehz6HaVk4+7Afhw=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.4", "", { "os": "sunos", "cpu": "x64" }, "sha512-Mw+tzy4pp6wZEK0+Lwr76pWLjrtjmJyUB23tHKqEDP74R3q95luY/bXqXZeYl4NYlvwOqoRKlInQialgCKy67Q=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-AVUP428VQTSddguz9dO9ngb+E5aScyg7nOeJDrF1HPYu555gmza3bDGMPhmVXL8svDSoqPCsCPjb265yG/kLKQ=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-i1sW+1i+oWvQzSgfRcxxG2k4I9n3O9NRqy8U+uugaT2Dy7kLO9Y7wI72haOahxceMX8hZAzgGou1FhndRldxRg=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.4", "", { "os": "win32", "cpu": "x64" }, "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ=="], + + "@grpc/grpc-js": ["@grpc/grpc-js@1.13.3", "", { "dependencies": { "@grpc/proto-loader": "^0.7.13", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-FTXHdOoPbZrBjlVLHuKbDZnsTxXv2BlHF57xw6LuThXacXvtkahEPED0CKMk6obZDf65Hv4k3z62eyPNpvinIg=="], + + "@grpc/proto-loader": ["@grpc/proto-loader@0.7.15", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="], + + "@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], + + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.8", "", { "dependencies": { "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/set-array": ["@jridgewell/set-array@1.2.1", "", {}, "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.0", "", {}, "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], + + "@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="], + + "@langchain/core": ["@langchain/core@0.3.56", "", { "dependencies": { "@cfworker/json-schema": "^4.0.2", "ansi-styles": "^5.0.0", "camelcase": "6", "decamelize": "1.2.0", "js-tiktoken": "^1.0.12", "langsmith": "^0.3.29", "mustache": "^4.2.0", "p-queue": "^6.6.2", "p-retry": "4", "uuid": "^10.0.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" } }, "sha512-eF9MyInM9RLNisAygiCrzHnqzOnuzGWy4f1SAqAis+XIMhcA98WuZDNWxyX9pP3aKQGc47FAJ/9XWJwv5KiquA=="], + + "@langchain/openai": ["@langchain/openai@0.5.10", "", { "dependencies": { "js-tiktoken": "^1.0.12", "openai": "^4.96.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" }, "peerDependencies": { "@langchain/core": ">=0.3.48 <0.4.0" } }, "sha512-hBQIWjcVxGS7tgVvgBBmrZ5jSaJ8nu9g6V64/Tx6KGjkW7VdGmUvqCO+koiQCOZVL7PBJkHWAvDsbghPYXiZEA=="], + + "@langchain/textsplitters": ["@langchain/textsplitters@0.1.0", "", { "dependencies": { "js-tiktoken": "^1.0.12" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" } }, "sha512-djI4uw9rlkAb5iMhtLED+xJebDdAG935AdP4eRTB02R7OB/act55Bj9wsskhZsvuyQRpO4O1wQOp85s6T6GWmw=="], + + "@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], + + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], + + "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="], + + "@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.53.0", "", { "dependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-8HArjKx+RaAI8uEIgcORbZIPklyh1YLjPSBus8hjRmvLi6DeFzgOcdZ7KwPabKj8mXF8dX0hyfAyGfycz0DbFw=="], + + "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@1.26.0", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-HedpXXYzzbaoutw6DFLWLDket2FwLkLpil4hGCZ1xYEIMTcivdfwEOISgdbLEWyG3HW52gTq2V9mOVJrONgiwg=="], + + "@opentelemetry/core": ["@opentelemetry/core@1.26.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1iKxXXE8415Cdv0yjG3G6hQnB5eVEsJce3QaawX8SjDn0mAS0ZM8fAbZZJD4ajvhC15cePvosSCut404KrIIvQ=="], + + "@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/exporter-logs-otlp-grpc@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-grpc-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/sdk-logs": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-x5ygAQgWAQOI+UOhyV3z9eW7QU2dCfnfOuIBiyYmC2AWr74f6x/3JBnP27IAcEx6aihpqBYWKnpoUTztkVPAZw=="], + + "@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/sdk-logs": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-cSRKgD/n8rb+Yd+Cif6EnHEL/VZg1o8lEcEwFji1lwene6BdH51Zh3feAD9p2TyVoBKrl6Q9Zm2WltSp2k9gWQ=="], + + "@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-jhEcVL1deeWNmTUP05UZMriZPSWUBcfg94ng7JuBb1q2NExgnADQFl1VQQ+xo62/JepK+MxQe4xAwlsDQFbISA=="], + + "@opentelemetry/exporter-trace-otlp-grpc": ["@opentelemetry/exporter-trace-otlp-grpc@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-grpc-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-m6KSh6OBDwfDjpzPVbuJbMgMbkoZfpxYH2r262KckgX9cMYvooWXEKzlJYsNDC6ADr28A1rtRoUVRwNfIN4tUg=="], + + "@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/exporter-trace-otlp-http@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-m7F5ZTq+V9mKGWYpX8EnZ7NjoqAU7VemQ1E2HAG+W/u0wpY1x0OmbxAXfGKFHCspdJk8UKlwPGrpcB8nay3P8A=="], + + "@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/exporter-trace-otlp-proto@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-T/bdXslwRKj23S96qbvGtaYOdfyew3TjPEKOk5mHjkCmkVl1O9C/YMdejwSsdLdOq2YW30KjR9kVi0YMxZushQ=="], + + "@opentelemetry/exporter-zipkin": ["@opentelemetry/exporter-zipkin@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-PW5R34n3SJHO4t0UetyHKiXL6LixIqWN6lWncg3eRXhKuT30x+b7m5sDJS0kEWRfHeS+kG7uCw2vBzmB2lk3Dw=="], + + "@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.200.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.200.0", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-pmPlzfJd+vvgaZd/reMsC8RWgTXn2WY1OWT5RT42m3aOn5532TozwXNDhg1vzqJ+jnvmkREcdLr27ebJEQt0Jg=="], + + "@opentelemetry/instrumentation-pg": ["@opentelemetry/instrumentation-pg@0.52.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.200.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0", "@types/pg": "8.6.1", "@types/pg-pool": "2.0.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-OBpqlxTqmFkZGHaHV4Pzd95HkyKVS+vf0N5wVX3BSb8uqsvOrW62I1qt+2jNsZ13dtG5eOzvcsQTMGND76wizA=="], + + "@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-transformer": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-UCWPreGQEhD6FjBaeDuXhiMf6kkBODF0ZQzrk/tuQcaVDJ+dDQ/xhJp192H9yWnKxVpEjFrSSLnpqmX4VwX+eA=="], + + "@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/otlp-grpc-exporter-base@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-F7RCN8VN+lzSa4fGjewit8Z5fEUpY/lmMVy5EWn2ZpbAabg3EE3sCLuTNfOiooNGnmvzimUPruoeqeko/5/TzQ=="], + + "@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-metrics": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-rM0sDA9HD8dluwuBxLetUmoqGJKSAbWenwD65KY9iZhUxdBHRLrIdrABfNDP7aiTjcgK8XFyTn5fhDz7N+W6DA=="], + + "@opentelemetry/propagator-b3": ["@opentelemetry/propagator-b3@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-vvVkQLQ/lGGyEy9GT8uFnI047pajSOVnZI2poJqVGD3nJ+B9sFGdlHNnQKophE3lHfnIH0pw2ubrCTjZCgIj+Q=="], + + "@opentelemetry/propagator-jaeger": ["@opentelemetry/propagator-jaeger@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-DelFGkCdaxA1C/QA0Xilszfr0t4YbGd3DjxiCDPh34lfnFr+VkkrjV9S8ZTJvAzfdKERXhfOxIKBoGPJwoSz7Q=="], + + "@opentelemetry/resources": ["@opentelemetry/resources@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-CPNYchBE7MBecCSVy0HKpUISEeJOniWqcHaAHpmasZ3j9o6V3AyBzhRc90jdmemq0HOxDr6ylhUbDhBqqPpeNw=="], + + "@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-dhSisnEgIj/vJZXZV6f6KcTnyLDx/VuQ6l3ejuZpMpPlh9S1qMHiZU9NMmOkVkwwHkMy3G6mEBwdP23vUZVr4g=="], + + "@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.30.1", "", { "dependencies": { "@opentelemetry/core": "1.30.1", "@opentelemetry/resources": "1.30.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog=="], + + "@opentelemetry/sdk-node": ["@opentelemetry/sdk-node@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/exporter-logs-otlp-grpc": "0.53.0", "@opentelemetry/exporter-logs-otlp-http": "0.53.0", "@opentelemetry/exporter-logs-otlp-proto": "0.53.0", "@opentelemetry/exporter-trace-otlp-grpc": "0.53.0", "@opentelemetry/exporter-trace-otlp-http": "0.53.0", "@opentelemetry/exporter-trace-otlp-proto": "0.53.0", "@opentelemetry/exporter-zipkin": "1.26.0", "@opentelemetry/instrumentation": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-metrics": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "@opentelemetry/sdk-trace-node": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0hsxfq3BKy05xGktwG8YdGdxV978++x40EAKyKr1CaHZRh8uqVlXnclnl7OMi9xLMJEcXUw7lGhiRlArFcovyg=="], + + "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-olWQldtvbK4v22ymrKLbIcBi9L2SpMO84sCPY54IVsJhP9fRsxJT194C/AVaAuJzLE30EdhhM1VmvVYR7az+cw=="], + + "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@1.26.0", "", { "dependencies": { "@opentelemetry/context-async-hooks": "1.26.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/propagator-b3": "1.26.0", "@opentelemetry/propagator-jaeger": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "semver": "^7.5.2" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Fj5IVKrj0yeUwlewCRwzOVcr5avTuNnMHWf7GPc1t6WaT78J6CJyF3saZ/0RkZfdeNO8IcBl/bNcWMVZBMRW8Q=="], + + "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.28.0", "", {}, "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA=="], + + "@opentelemetry/sql-common": ["@opentelemetry/sql-common@0.41.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" } }, "sha512-pmzXctVbEERbqSfiAgdes9Y63xjoOyXcD7B6IXBkVb+vbM7M9U98mn33nGXxPf4dfYR0M+vhcKRZmbSJ7HfqFA=="], + + "@phala/dstack-sdk": ["@phala/dstack-sdk@0.1.11", "", { "optionalDependencies": { "@noble/curves": "^1.8.1", "@solana/web3.js": "^1.98.0", "viem": "^2.21.0 <3.0.0" } }, "sha512-d1naX/bDGqCItpIzvvHSpytNR9zNPofYbsCJD7uy2zT+vDC5lLehqL2BeR1d7QVsnnNI0wXPiXTiMbwGS7fz0Q=="], + + "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="], + + "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="], + + "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], + + "@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="], + + "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="], + + "@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="], + + "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="], + + "@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="], + + "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="], + + "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="], + + "@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.40.2", "", { "os": "android", "cpu": "arm" }, "sha512-JkdNEq+DFxZfUwxvB58tHMHBHVgX23ew41g1OQinthJ+ryhdRk67O31S7sYw8u2lTjHUPFxwar07BBt1KHp/hg=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.40.2", "", { "os": "android", "cpu": "arm64" }, "sha512-13unNoZ8NzUmnndhPTkWPWbX3vtHodYmy+I9kuLxN+F+l+x3LdVF7UCu8TWVMt1POHLh6oDHhnOA04n8oJZhBw=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.40.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Gzf1Hn2Aoe8VZzevHostPX23U7N5+4D36WJNHK88NZHCJr7aVMG4fadqkIf72eqVPGjGc0HJHNuUaUcxiR+N/w=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.40.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-47N4hxa01a4x6XnJoskMKTS8XZ0CZMd8YTbINbi+w03A2w4j1RTlnGHOz/P0+Bg1LaVL6ufZyNprSg+fW5nYQQ=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.40.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-8t6aL4MD+rXSHHZUR1z19+9OFJ2rl1wGKvckN47XFRVO+QL/dUSpKA2SLRo4vMg7ELA8pzGpC+W9OEd1Z/ZqoQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.40.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-C+AyHBzfpsOEYRFjztcYUFsH4S7UsE9cDtHCtma5BK8+ydOZYgMmWg1d/4KBytQspJCld8ZIujFMAdKG1xyr4Q=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.40.2", "", { "os": "linux", "cpu": "arm" }, "sha512-de6TFZYIvJwRNjmW3+gaXiZ2DaWL5D5yGmSYzkdzjBDS3W+B9JQ48oZEsmMvemqjtAFzE16DIBLqd6IQQRuG9Q=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.40.2", "", { "os": "linux", "cpu": "arm" }, "sha512-urjaEZubdIkacKc930hUDOfQPysezKla/O9qV+O89enqsqUmQm8Xj8O/vh0gHg4LYfv7Y7UsE3QjzLQzDYN1qg=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.40.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-KlE8IC0HFOC33taNt1zR8qNlBYHj31qGT1UqWqtvR/+NuCVhfufAq9fxO8BMFC22Wu0rxOwGVWxtCMvZVLmhQg=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.40.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-j8CgxvfM0kbnhu4XgjnCWJQyyBOeBI1Zq91Z850aUddUmPeQvuAy6OiMdPS46gNFgy8gN1xkYyLgwLYZG3rBOg=="], + + "@rollup/rollup-linux-loongarch64-gnu": ["@rollup/rollup-linux-loongarch64-gnu@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-Ybc/1qUampKuRF4tQXc7G7QY9YRyeVSykfK36Y5Qc5dmrIxwFhrOzqaVTNoZygqZ1ZieSWTibfFhQ5qK8jpWxw=="], + + "@rollup/rollup-linux-powerpc64le-gnu": ["@rollup/rollup-linux-powerpc64le-gnu@4.40.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3FCIrnrt03CCsZqSYAOW/k9n625pjpuMzVfeI+ZBUSDT3MVIFDSPfSUgIl9FqUftxcUXInvFah79hE1c9abD+Q=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-QNU7BFHEvHMp2ESSY3SozIkBPaPBDTsfVNGx3Xhv+TdvWXFGOSH2NJvhD1zKAT6AyuuErJgbdvaJhYVhVqrWTg=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-5W6vNYkhgfh7URiXTO1E9a0cy4fSgfE4+Hl5agb/U1sa0kjOLMLC1wObxwKxecE17j0URxuTrYZZME4/VH57Hg=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.40.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-B7LKIz+0+p348JoAL4X/YxGx9zOx3sR+o6Hj15Y3aaApNfAshK8+mWZEf759DXfRLeL2vg5LYJBB7DdcleYCoQ=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.40.2", "", { "os": "linux", "cpu": "x64" }, "sha512-lG7Xa+BmBNwpjmVUbmyKxdQJ3Q6whHjMjzQplOs5Z+Gj7mxPtWakGHqzMqNER68G67kmCX9qX57aRsW5V0VOng=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.40.2", "", { "os": "linux", "cpu": "x64" }, "sha512-tD46wKHd+KJvsmije4bUskNuvWKFcTOIM9tZ/RrmIvcXnbi0YK/cKS9FzFtAm7Oxi2EhV5N2OpfFB348vSQRXA=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.40.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Bjv/HG8RRWLNkXwQQemdsWw4Mg+IJ29LK+bJPW2SCzPKOUaMmPEppQlu/Fqk1d7+DX3V7JbFdbkh/NMmurT6Pg=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.40.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-dt1llVSGEsGKvzeIO76HToiYPNPYPkmjhMHhP00T9S4rDern8P2ZWvWAQUEJ+R1UdMWJ/42i/QqJ2WV765GZcA=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.40.2", "", { "os": "win32", "cpu": "x64" }, "sha512-bwspbWB04XJpeElvsp+DCylKfF4trJDa2Y9Go8O6A7YLX2LIKGcNK/CYImJN6ZP4DcuOHB4Utl3iCbnR62DudA=="], + + "@scure/base": ["@scure/base@1.2.5", "", {}, "sha512-9rE6EOVeIQzt5TSu4v+K523F8u6DhBsoZWPGKlnCshhlDhy0kJzUX4V+tr2dWmzF1GdekvThABoEQBGBQI7xZw=="], + + "@scure/bip32": ["@scure/bip32@1.6.2", "", { "dependencies": { "@noble/curves": "~1.8.1", "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.2" } }, "sha512-t96EPDMbtGgtb7onKKqxRLfE5g05k7uHnHRM2xdE6BP/ZmxaLtPek4J4KfVn/90IQNrU1IOAqMgiDtUdtbe3nw=="], + + "@scure/bip39": ["@scure/bip39@1.5.4", "", { "dependencies": { "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.4" } }, "sha512-TFM4ni0vKvCfBpohoh+/lY05i9gRbSwXWngAsF4CABQxoaOHijxuaZ2R6cStDQ5CHtHO9aGJTr4ksVJASRRyMA=="], + + "@solana/buffer-layout": ["@solana/buffer-layout@4.0.1", "", { "dependencies": { "buffer": "~6.0.3" } }, "sha512-E1ImOIAD1tBZFRdjeM4/pzTiTApC0AOBGwyAMS4fwIodCWArzJ3DWdoh8cKxeFM2fElkxBh2Aqts1BPC373rHA=="], + + "@solana/codecs-core": ["@solana/codecs-core@2.1.1", "", { "dependencies": { "@solana/errors": "2.1.1" }, "peerDependencies": { "typescript": ">=5.3.3" } }, "sha512-iPQW3UZ2Vi7QFBo2r9tw0NubtH8EdrhhmZulx6lC8V5a+qjaxovtM/q/UW2BTNpqqHLfO0tIcLyBLrNH4HTWPg=="], + + "@solana/codecs-numbers": ["@solana/codecs-numbers@2.1.1", "", { "dependencies": { "@solana/codecs-core": "2.1.1", "@solana/errors": "2.1.1" }, "peerDependencies": { "typescript": ">=5.3.3" } }, "sha512-m20IUPJhPUmPkHSlZ2iMAjJ7PaYUvlMtFhCQYzm9BEBSI6OCvXTG3GAPpAnSGRBfg5y+QNqqmKn4QHU3B6zzCQ=="], + + "@solana/errors": ["@solana/errors@2.1.1", "", { "dependencies": { "chalk": "^5.4.1", "commander": "^13.1.0" }, "peerDependencies": { "typescript": ">=5.3.3" }, "bin": { "errors": "bin/cli.mjs" } }, "sha512-sj6DaWNbSJFvLzT8UZoabMefQUfSW/8tXK7NTiagsDmh+Q87eyQDDC9L3z+mNmx9b6dEf6z660MOIplDD2nfEw=="], + + "@solana/web3.js": ["@solana/web3.js@1.98.2", "", { "dependencies": { "@babel/runtime": "^7.25.0", "@noble/curves": "^1.4.2", "@noble/hashes": "^1.4.0", "@solana/buffer-layout": "^4.0.1", "@solana/codecs-numbers": "^2.1.0", "agentkeepalive": "^4.5.0", "bn.js": "^5.2.1", "borsh": "^0.7.0", "bs58": "^4.0.1", "buffer": "6.0.3", "fast-stable-stringify": "^1.0.0", "jayson": "^4.1.1", "node-fetch": "^2.7.0", "rpc-websockets": "^9.0.2", "superstruct": "^2.0.2" } }, "sha512-BqVwEG+TaG2yCkBMbD3C4hdpustR4FpuUFRPUmqRZYYlPI9Hg4XMWxHWOWRzHE9Lkc9NDjzXFX7lDXSgzC7R1A=="], + + "@swc/helpers": ["@swc/helpers@0.5.17", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A=="], + + "@types/connect": ["@types/connect@3.4.38", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="], + + "@types/estree": ["@types/estree@1.0.7", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="], + + "@types/node": ["@types/node@22.15.18", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-v1DKRfUdyW+jJhZNEI1PYy29S2YRxMV5AOO/x/SjKmW0acCIOqmbj6Haf9eHAhsPmrhlHSxEhv/1WszcLWV4cg=="], + + "@types/node-fetch": ["@types/node-fetch@2.6.12", "", { "dependencies": { "@types/node": "*", "form-data": "^4.0.0" } }, "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA=="], + + "@types/pg": ["@types/pg@8.6.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-1Kc4oAGzAl7uqUStZCDvaLFqZrW9qWSjXOmBfdgyBP5La7Us6Mg4GBvRlSoaZMhQF/zSj1C8CtKMBkoiT8eL8w=="], + + "@types/pg-pool": ["@types/pg-pool@2.0.6", "", { "dependencies": { "@types/pg": "*" } }, "sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ=="], + + "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], + + "@types/shimmer": ["@types/shimmer@1.2.0", "", {}, "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg=="], + + "@types/uuid": ["@types/uuid@8.3.4", "", {}, "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw=="], + + "@types/ws": ["@types/ws@7.4.7", "", { "dependencies": { "@types/node": "*" } }, "sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww=="], + + "@vitest/expect": ["@vitest/expect@3.1.3", "", { "dependencies": { "@vitest/spy": "3.1.3", "@vitest/utils": "3.1.3", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-7FTQQuuLKmN1Ig/h+h/GO+44Q1IlglPlR2es4ab7Yvfx+Uk5xsv+Ykk+MEt/M2Yn/xGmzaLKxGw2lgy2bwuYqg=="], + + "@vitest/mocker": ["@vitest/mocker@3.1.3", "", { "dependencies": { "@vitest/spy": "3.1.3", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-PJbLjonJK82uCWHjzgBJZuR7zmAOrSvKk1QBxrennDIgtH4uK0TB1PvYmc0XBCigxxtiAVPfWtAdy4lpz8SQGQ=="], + + "@vitest/pretty-format": ["@vitest/pretty-format@3.1.3", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-i6FDiBeJUGLDKADw2Gb01UtUNb12yyXAqC/mmRWuYl+m/U9GS7s8us5ONmGkGpUUo7/iAYzI2ePVfOZTYvUifA=="], + + "@vitest/runner": ["@vitest/runner@3.1.3", "", { "dependencies": { "@vitest/utils": "3.1.3", "pathe": "^2.0.3" } }, "sha512-Tae+ogtlNfFei5DggOsSUvkIaSuVywujMj6HzR97AHK6XK8i3BuVyIifWAm/sE3a15lF5RH9yQIrbXYuo0IFyA=="], + + "@vitest/snapshot": ["@vitest/snapshot@3.1.3", "", { "dependencies": { "@vitest/pretty-format": "3.1.3", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-XVa5OPNTYUsyqG9skuUkFzAeFnEzDp8hQu7kZ0N25B1+6KjGm4hWLtURyBbsIAOekfWQ7Wuz/N/XXzgYO3deWQ=="], + + "@vitest/spy": ["@vitest/spy@3.1.3", "", { "dependencies": { "tinyspy": "^3.0.2" } }, "sha512-x6w+ctOEmEXdWaa6TO4ilb7l9DxPR5bwEb6hILKuxfU1NqWT2mpJD9NJN7t3OTfxmVlOMrvtoFJGdgyzZ605lQ=="], + + "@vitest/utils": ["@vitest/utils@3.1.3", "", { "dependencies": { "@vitest/pretty-format": "3.1.3", "loupe": "^3.1.3", "tinyrainbow": "^2.0.0" } }, "sha512-2Ltrpht4OmHO9+c/nmHtF09HWiyWdworqnHIwjfvDyWjuwKbdkcS9AnhsDn+8E2RM4x++foD1/tNuLPVvWG1Rg=="], + + "abitype": ["abitype@1.0.8", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3 >=3.22.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-ZeiI6h3GnW06uYDLx0etQtX/p8E24UaHHBj57RSjK7YBFe7iuVn07EDpOeP451D06sF27VOz9JJPlIKJmXgkEg=="], + + "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], + + "acorn": ["acorn@8.14.1", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg=="], + + "acorn-import-attributes": ["acorn-import-attributes@1.9.5", "", { "peerDependencies": { "acorn": "^8" } }, "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ=="], + + "agentkeepalive": ["agentkeepalive@4.6.0", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="], + + "ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], + + "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], + + "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], + + "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "asn1.js": ["asn1.js@4.10.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw=="], + + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + + "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], + + "atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + + "base-x": ["base-x@3.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-xz7wQ8xDhdyP7tQxwdteLYeFfS68tSMNCZ/Y37WJ4bhGfKPpqEIlmIyueQHqOyoPhE6xNUqjzRr8ra0eF9VRvA=="], + + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], + + "bigint-buffer": ["bigint-buffer@1.1.5", "", { "dependencies": { "bindings": "^1.3.0" } }, "sha512-trfYco6AoZ+rKhKnxA0hgX0HAbVP/s808/EuDSe2JDzUnCp/xAsli35Orvk67UrTEcwuxZqYZDmfA2RXJgxVvA=="], + + "bindings": ["bindings@1.5.0", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="], + + "bn.js": ["bn.js@5.2.2", "", {}, "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw=="], + + "borsh": ["borsh@0.7.0", "", { "dependencies": { "bn.js": "^5.2.0", "bs58": "^4.0.0", "text-encoding-utf-8": "^1.0.2" } }, "sha512-CLCsZGIBCFnPtkNnieW/a8wmreDmfUtjU2m9yHrzPXIlNbqVs0AQrSatSG6vdNYUqdc83tkQi2eHfF98ubzQLA=="], + + "brace-expansion": ["brace-expansion@2.0.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="], + + "brorand": ["brorand@1.1.0", "", {}, "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w=="], + + "browserify-aes": ["browserify-aes@1.2.0", "", { "dependencies": { "buffer-xor": "^1.0.3", "cipher-base": "^1.0.0", "create-hash": "^1.1.0", "evp_bytestokey": "^1.0.3", "inherits": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA=="], + + "browserify-cipher": ["browserify-cipher@1.0.1", "", { "dependencies": { "browserify-aes": "^1.0.4", "browserify-des": "^1.0.0", "evp_bytestokey": "^1.0.0" } }, "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w=="], + + "browserify-des": ["browserify-des@1.0.2", "", { "dependencies": { "cipher-base": "^1.0.1", "des.js": "^1.0.0", "inherits": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A=="], + + "browserify-rsa": ["browserify-rsa@4.1.1", "", { "dependencies": { "bn.js": "^5.2.1", "randombytes": "^2.1.0", "safe-buffer": "^5.2.1" } }, "sha512-YBjSAiTqM04ZVei6sXighu679a3SqWORA3qZTEqZImnlkDIFtKc6pNutpjyZ8RJTjQtuYfeetkxM11GwoYXMIQ=="], + + "browserify-sign": ["browserify-sign@4.2.3", "", { "dependencies": { "bn.js": "^5.2.1", "browserify-rsa": "^4.1.0", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", "elliptic": "^6.5.5", "hash-base": "~3.0", "inherits": "^2.0.4", "parse-asn1": "^5.1.7", "readable-stream": "^2.3.8", "safe-buffer": "^5.2.1" } }, "sha512-JWCZW6SKhfhjJxO8Tyiiy+XYB7cqd2S5/+WeYHsKdNKFlCBhKbblba1A/HN/90YwtxKc8tCErjffZl++UNmGiw=="], + + "bs58": ["bs58@4.0.1", "", { "dependencies": { "base-x": "^3.0.2" } }, "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw=="], + + "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], + + "buffer-xor": ["buffer-xor@1.0.3", "", {}, "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ=="], + + "bufferutil": ["bufferutil@4.0.9", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-WDtdLmJvAuNNPzByAYpRo2rF1Mmradw6gvWsQKf63476DDXmomT9zUiGypLcG4ibIM67vhAj8jJRdbmEws2Aqw=="], + + "bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="], + + "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "camelcase": ["camelcase@6.3.0", "", {}, "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA=="], + + "chai": ["chai@5.2.0", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw=="], + + "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "check-error": ["check-error@2.1.1", "", {}, "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw=="], + + "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + + "cipher-base": ["cipher-base@1.0.6", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1" } }, "sha512-3Ek9H3X6pj5TgenXYtNWdaBon1tgYCaebd+XPg0keyjEbEfkD4KkmAxkQ/i1vYvxdcT5nscLBfq9VJRmCBcFSw=="], + + "cjs-module-lexer": ["cjs-module-lexer@1.4.3", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="], + + "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="], + + "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], + + "commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], + + "confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="], + + "consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="], + + "console-table-printer": ["console-table-printer@2.12.1", "", { "dependencies": { "simple-wcswidth": "^1.0.1" } }, "sha512-wKGOQRRvdnd89pCeH96e2Fn4wkbenSP6LMHfjfyNLMbGuHEFbMqQNuxXqd0oXG9caIOQ1FTvc5Uijp9/4jujnQ=="], + + "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], + + "create-ecdh": ["create-ecdh@4.0.4", "", { "dependencies": { "bn.js": "^4.1.0", "elliptic": "^6.5.3" } }, "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A=="], + + "create-hash": ["create-hash@1.2.0", "", { "dependencies": { "cipher-base": "^1.0.1", "inherits": "^2.0.1", "md5.js": "^1.3.4", "ripemd160": "^2.0.1", "sha.js": "^2.4.0" } }, "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg=="], + + "create-hmac": ["create-hmac@1.1.7", "", { "dependencies": { "cipher-base": "^1.0.3", "create-hash": "^1.1.0", "inherits": "^2.0.1", "ripemd160": "^2.0.0", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "crypto-browserify": ["crypto-browserify@3.12.1", "", { "dependencies": { "browserify-cipher": "^1.0.1", "browserify-sign": "^4.2.3", "create-ecdh": "^4.0.4", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", "diffie-hellman": "^5.0.3", "hash-base": "~3.0.4", "inherits": "^2.0.4", "pbkdf2": "^3.1.2", "public-encrypt": "^4.0.3", "randombytes": "^2.1.0", "randomfill": "^1.0.4" } }, "sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ=="], + + "dateformat": ["dateformat@4.6.3", "", {}, "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA=="], + + "debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="], + + "decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="], + + "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], + + "delay": ["delay@5.0.0", "", {}, "sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw=="], + + "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], + + "des.js": ["des.js@1.1.0", "", { "dependencies": { "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg=="], + + "diffie-hellman": ["diffie-hellman@5.0.3", "", { "dependencies": { "bn.js": "^4.1.0", "miller-rabin": "^4.0.0", "randombytes": "^2.0.0" } }, "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg=="], + + "dotenv": ["dotenv@16.4.5", "", {}, "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg=="], + + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + + "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], + + "elliptic": ["elliptic@6.6.1", "", { "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", "inherits": "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g=="], + + "emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], + + "end-of-stream": ["end-of-stream@1.4.4", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], + + "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], + + "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], + + "es6-promise": ["es6-promise@4.2.8", "", {}, "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w=="], + + "es6-promisify": ["es6-promisify@5.0.0", "", { "dependencies": { "es6-promise": "^4.0.3" } }, "sha512-C+d6UdsYDk0lMebHNR4S2NybQMMngAOnOwYBQjTOiv0MkoJMP0Myw2mgpDLBcpfCmRLxyFqYhS/CfOENq4SJhQ=="], + + "esbuild": ["esbuild@0.25.4", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.4", "@esbuild/android-arm": "0.25.4", "@esbuild/android-arm64": "0.25.4", "@esbuild/android-x64": "0.25.4", "@esbuild/darwin-arm64": "0.25.4", "@esbuild/darwin-x64": "0.25.4", "@esbuild/freebsd-arm64": "0.25.4", "@esbuild/freebsd-x64": "0.25.4", "@esbuild/linux-arm": "0.25.4", "@esbuild/linux-arm64": "0.25.4", "@esbuild/linux-ia32": "0.25.4", "@esbuild/linux-loong64": "0.25.4", "@esbuild/linux-mips64el": "0.25.4", "@esbuild/linux-ppc64": "0.25.4", "@esbuild/linux-riscv64": "0.25.4", "@esbuild/linux-s390x": "0.25.4", "@esbuild/linux-x64": "0.25.4", "@esbuild/netbsd-arm64": "0.25.4", "@esbuild/netbsd-x64": "0.25.4", "@esbuild/openbsd-arm64": "0.25.4", "@esbuild/openbsd-x64": "0.25.4", "@esbuild/sunos-x64": "0.25.4", "@esbuild/win32-arm64": "0.25.4", "@esbuild/win32-ia32": "0.25.4", "@esbuild/win32-x64": "0.25.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q=="], + + "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + + "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], + + "eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], + + "events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="], + + "evp_bytestokey": ["evp_bytestokey@1.0.3", "", { "dependencies": { "md5.js": "^1.3.4", "safe-buffer": "^5.1.1" } }, "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA=="], + + "expect-type": ["expect-type@1.2.1", "", {}, "sha512-/kP8CAwxzLVEeFrMm4kMmy4CCDlpipyA7MYLVrdJIkV0fYF0UaigQHRsxHiuY/GEea+bh4KSv3TIlgr+2UL6bw=="], + + "eyes": ["eyes@0.1.8", "", {}, "sha512-GipyPsXO1anza0AOZdy69Im7hGFCNB7Y/NGjDlZGJ3GJJLtwNSb2vrzYrTYJRrRloVx7pl+bhUaTB8yiccPvFQ=="], + + "fast-copy": ["fast-copy@3.0.2", "", {}, "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ=="], + + "fast-redact": ["fast-redact@3.5.0", "", {}, "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A=="], + + "fast-safe-stringify": ["fast-safe-stringify@2.1.1", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="], + + "fast-stable-stringify": ["fast-stable-stringify@1.0.0", "", {}, "sha512-wpYMUmFu5f00Sm0cj2pfivpmawLZ0NKdviQ4w9zJeR8JVtOpOxHmLaJuj0vxvGqMJQWyP/COUkF75/57OKyRag=="], + + "fdir": ["fdir@6.4.4", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg=="], + + "file-uri-to-path": ["file-uri-to-path@1.0.0", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="], + + "fix-dts-default-cjs-exports": ["fix-dts-default-cjs-exports@1.0.1", "", { "dependencies": { "magic-string": "^0.30.17", "mlly": "^1.7.4", "rollup": "^4.34.8" } }, "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg=="], + + "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], + + "form-data": ["form-data@4.0.2", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "mime-types": "^2.1.12" } }, "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w=="], + + "form-data-encoder": ["form-data-encoder@1.7.2", "", {}, "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="], + + "formdata-node": ["formdata-node@4.4.1", "", { "dependencies": { "node-domexception": "1.0.0", "web-streams-polyfill": "4.0.0-beta.3" } }, "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + + "glob": ["glob@11.0.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^4.0.1", "minimatch": "^10.0.0", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "handlebars": ["handlebars@4.7.8", "", { "dependencies": { "minimist": "^1.2.5", "neo-async": "^2.6.2", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "optionalDependencies": { "uglify-js": "^3.1.4" }, "bin": { "handlebars": "bin/handlebars" } }, "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ=="], + + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], + + "hash-base": ["hash-base@3.0.5", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1" } }, "sha512-vXm0l45VbcHEVlTCzs8M+s0VeYsB2lnlAaThoLKGXr3bE/VWDOelNUnycUPEhKEaXARL2TEFjBOyUiM6+55KBg=="], + + "hash.js": ["hash.js@1.1.7", "", { "dependencies": { "inherits": "^2.0.3", "minimalistic-assert": "^1.0.1" } }, "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA=="], + + "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], + + "help-me": ["help-me@5.0.0", "", {}, "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="], + + "hmac-drbg": ["hmac-drbg@1.0.1", "", { "dependencies": { "hash.js": "^1.0.3", "minimalistic-assert": "^1.0.0", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg=="], + + "humanize-ms": ["humanize-ms@1.2.1", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="], + + "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], + + "import-in-the-middle": ["import-in-the-middle@1.13.2", "", { "dependencies": { "acorn": "^8.14.0", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" } }, "sha512-Yjp9X7s2eHSXvZYQ0aye6UvwYPrVB5C2k47fuXjFKnYinAByaDZjh4t9MT2wEga9775n6WaIqyHnQhBxYtX2mg=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "is-core-module": ["is-core-module@2.16.1", "", { "dependencies": { "hasown": "^2.0.2" } }, "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w=="], + + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + + "isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "isomorphic-ws": ["isomorphic-ws@4.0.1", "", { "peerDependencies": { "ws": "*" } }, "sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w=="], + + "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], + + "jackspeak": ["jackspeak@4.1.0", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" } }, "sha512-9DDdhb5j6cpeitCbvLO7n7J4IxnbM6hoF6O1g4HQ5TfhvvKN8ywDM7668ZhMHRqVmxqhps/F6syWK2KcPxYlkw=="], + + "jayson": ["jayson@4.2.0", "", { "dependencies": { "@types/connect": "^3.4.33", "@types/node": "^12.12.54", "@types/ws": "^7.4.4", "commander": "^2.20.3", "delay": "^5.0.0", "es6-promisify": "^5.0.0", "eyes": "^0.1.8", "isomorphic-ws": "^4.0.1", "json-stringify-safe": "^5.0.1", "stream-json": "^1.9.1", "uuid": "^8.3.2", "ws": "^7.5.10" }, "bin": { "jayson": "bin/jayson.js" } }, "sha512-VfJ9t1YLwacIubLhONk0KFeosUBwstRWQ0IRT1KDjEjnVnSOVHC3uwugyV7L0c7R9lpVyrUGT2XWiBA1UTtpyg=="], + + "joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="], + + "js-sha1": ["js-sha1@0.7.0", "", {}, "sha512-oQZ1Mo7440BfLSv9TX87VNEyU52pXPVG19F9PL3gTgNt0tVxlZ8F4O6yze3CLuLx28TxotxvlyepCNaaV0ZjMw=="], + + "js-tiktoken": ["js-tiktoken@1.0.20", "", { "dependencies": { "base64-js": "^1.5.1" } }, "sha512-Xlaqhhs8VfCd6Sh7a1cFkZHQbYTLCwVJJWiHVxBYzLPxW0XsoxBy1hitmjkdIjD3Aon5BXLHFwU5O8WUx6HH+A=="], + + "js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="], + + "json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="], + + "jsonpointer": ["jsonpointer@5.0.1", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="], + + "langchain": ["langchain@0.3.26", "", { "dependencies": { "@langchain/openai": ">=0.1.0 <0.6.0", "@langchain/textsplitters": ">=0.0.0 <0.2.0", "js-tiktoken": "^1.0.12", "js-yaml": "^4.1.0", "jsonpointer": "^5.0.1", "langsmith": "^0.3.29", "openapi-types": "^12.1.3", "p-retry": "4", "uuid": "^10.0.0", "yaml": "^2.2.1", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" }, "peerDependencies": { "@langchain/anthropic": "*", "@langchain/aws": "*", "@langchain/cerebras": "*", "@langchain/cohere": "*", "@langchain/core": ">=0.2.21 <0.4.0", "@langchain/deepseek": "*", "@langchain/google-genai": "*", "@langchain/google-vertexai": "*", "@langchain/google-vertexai-web": "*", "@langchain/groq": "*", "@langchain/mistralai": "*", "@langchain/ollama": "*", "@langchain/xai": "*", "axios": "*", "cheerio": "*", "handlebars": "^4.7.8", "peggy": "^3.0.2", "typeorm": "*" }, "optionalPeers": ["@langchain/anthropic", "@langchain/aws", "@langchain/cerebras", "@langchain/cohere", "@langchain/deepseek", "@langchain/google-genai", "@langchain/google-vertexai", "@langchain/google-vertexai-web", "@langchain/groq", "@langchain/mistralai", "@langchain/ollama", "@langchain/xai", "axios", "cheerio", "handlebars", "peggy", "typeorm"] }, "sha512-W/9phB4wiAnj+PnpMWmv/ptIp7i5ygY2aK8yjKlxccHPbaNeMoy7njzFz8d0/xfcPyA3MvG4AuZnJ1j3/E2/Ig=="], + + "langsmith": ["langsmith@0.3.29", "", { "dependencies": { "@types/uuid": "^10.0.0", "chalk": "^4.1.2", "console-table-printer": "^2.12.1", "p-queue": "^6.6.2", "p-retry": "4", "semver": "^7.6.3", "uuid": "^10.0.0" }, "peerDependencies": { "openai": "*" }, "optionalPeers": ["openai"] }, "sha512-JPF2B339qpYy9FyuY4Yz1aWYtgPlFc/a+VTj3L/JcFLHCiMP7+Ig8I9jO+o1QwVa+JU3iugL1RS0wwc+Glw0zA=="], + + "lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="], + + "lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="], + + "load-tsconfig": ["load-tsconfig@0.2.5", "", {}, "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg=="], + + "lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="], + + "lodash.sortby": ["lodash.sortby@4.7.0", "", {}, "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA=="], + + "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + + "loupe": ["loupe@3.1.3", "", {}, "sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug=="], + + "lru-cache": ["lru-cache@11.1.0", "", {}, "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A=="], + + "magic-string": ["magic-string@0.30.17", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="], + + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + + "md5.js": ["md5.js@1.3.5", "", { "dependencies": { "hash-base": "^3.0.0", "inherits": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg=="], + + "miller-rabin": ["miller-rabin@4.0.1", "", { "dependencies": { "bn.js": "^4.0.0", "brorand": "^1.0.1" }, "bin": { "miller-rabin": "bin/miller-rabin" } }, "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA=="], + + "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + + "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + + "minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="], + + "minimalistic-crypto-utils": ["minimalistic-crypto-utils@1.0.1", "", {}, "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg=="], + + "minimatch": ["minimatch@10.0.1", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + + "minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="], + + "mlly": ["mlly@1.7.4", "", { "dependencies": { "acorn": "^8.14.0", "pathe": "^2.0.1", "pkg-types": "^1.3.0", "ufo": "^1.5.4" } }, "sha512-qmdSIPC4bDJXgZTCR7XosJiNKySV7O215tsPtDN9iEO/7q/76b/ijtgRu/+epFXSJhijtTCCGp3DWS549P3xKw=="], + + "module-details-from-path": ["module-details-from-path@1.0.4", "", {}, "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "mustache": ["mustache@4.2.0", "", { "bin": { "mustache": "bin/mustache" } }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="], + + "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], + + "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], + + "neo-async": ["neo-async@2.6.2", "", {}, "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw=="], + + "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], + + "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], + + "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], + + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + + "openai": ["openai@4.100.0", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" }, "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-9soq/wukv3utxcuD7TWFqKdKp0INWdeyhUCvxwrne5KwnxaCp4eHL4GdT/tMFhYolxgNhxFzg5GFwM331Z5CZg=="], + + "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], + + "ox": ["ox@0.6.9", "", { "dependencies": { "@adraffy/ens-normalize": "^1.10.1", "@noble/curves": "^1.6.0", "@noble/hashes": "^1.5.0", "@scure/bip32": "^1.5.0", "@scure/bip39": "^1.4.0", "abitype": "^1.0.6", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug=="], + + "p-finally": ["p-finally@1.0.0", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="], + + "p-queue": ["p-queue@6.6.2", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="], + + "p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="], + + "p-timeout": ["p-timeout@3.2.0", "", { "dependencies": { "p-finally": "^1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="], + + "package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="], + + "parse-asn1": ["parse-asn1@5.1.7", "", { "dependencies": { "asn1.js": "^4.10.1", "browserify-aes": "^1.2.0", "evp_bytestokey": "^1.0.3", "hash-base": "~3.0", "pbkdf2": "^3.1.2", "safe-buffer": "^5.2.1" } }, "sha512-CTM5kuWR3sx9IFamcl5ErfPl6ea/N8IYwiJ+vpeB2g+1iknv7zBl5uPwbMbRVznRVbrNY6lGuDoE5b30grmbqg=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="], + + "path-scurry": ["path-scurry@2.0.0", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "pathval": ["pathval@2.0.0", "", {}, "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA=="], + + "pbkdf2": ["pbkdf2@3.1.2", "", { "dependencies": { "create-hash": "^1.1.2", "create-hmac": "^1.1.4", "ripemd160": "^2.0.1", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA=="], + + "pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="], + + "pg-protocol": ["pg-protocol@1.10.0", "", {}, "sha512-IpdytjudNuLv8nhlHs/UrVBhU0e78J0oIS/0AVdTbWxSOkFUVdsHC/NrorO6nXsQNDTT1kzDSOMJubBQviX18Q=="], + + "pg-types": ["pg-types@2.2.0", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.2", "", {}, "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg=="], + + "pino": ["pino@9.6.0", "", { "dependencies": { "atomic-sleep": "^1.0.0", "fast-redact": "^3.1.1", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^4.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^3.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-i85pKRCt4qMjZ1+L7sy2Ag4t1atFcdbEt76+7iRJn1g2BvsnRMGu9p8pivl9fs63M2kF/A0OacFZhTub+m/qMg=="], + + "pino-abstract-transport": ["pino-abstract-transport@2.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw=="], + + "pino-pretty": ["pino-pretty@13.0.0", "", { "dependencies": { "colorette": "^2.0.7", "dateformat": "^4.6.3", "fast-copy": "^3.0.2", "fast-safe-stringify": "^2.1.1", "help-me": "^5.0.0", "joycon": "^3.1.1", "minimist": "^1.2.6", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pump": "^3.0.0", "secure-json-parse": "^2.4.0", "sonic-boom": "^4.0.1", "strip-json-comments": "^3.1.1" }, "bin": { "pino-pretty": "bin.js" } }, "sha512-cQBBIVG3YajgoUjo1FdKVRX6t9XPxwB9lcNJVD5GCnNM4Y6T12YYx8c6zEejxQsU0wrg9TwmDulcE9LR7qcJqA=="], + + "pino-std-serializers": ["pino-std-serializers@7.0.0", "", {}, "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA=="], + + "pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="], + + "pkg-types": ["pkg-types@1.3.1", "", { "dependencies": { "confbox": "^0.1.8", "mlly": "^1.7.4", "pathe": "^2.0.1" } }, "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ=="], + + "postcss": ["postcss@8.5.3", "", { "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A=="], + + "postcss-load-config": ["postcss-load-config@6.0.1", "", { "dependencies": { "lilconfig": "^3.1.1" }, "peerDependencies": { "jiti": ">=1.21.0", "postcss": ">=8.0.9", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "postcss", "tsx", "yaml"] }, "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g=="], + + "postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="], + + "postgres-bytea": ["postgres-bytea@1.0.0", "", {}, "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w=="], + + "postgres-date": ["postgres-date@1.0.7", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="], + + "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], + + "prettier": ["prettier@3.5.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw=="], + + "process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="], + + "process-warning": ["process-warning@4.0.1", "", {}, "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q=="], + + "protobufjs": ["protobufjs@7.5.2", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-f2ls6rpO6G153Cy+o2XQ+Y0sARLOZ17+OGVLHrc3VUKcLHYKEKWbkSujdBWQXM7gKn5NTfp0XnRPZn1MIu8n9w=="], + + "public-encrypt": ["public-encrypt@4.0.3", "", { "dependencies": { "bn.js": "^4.1.0", "browserify-rsa": "^4.0.0", "create-hash": "^1.1.0", "parse-asn1": "^5.0.0", "randombytes": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q=="], + + "pump": ["pump@3.0.2", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="], + + "randombytes": ["randombytes@2.1.0", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="], + + "randomfill": ["randomfill@1.0.4", "", { "dependencies": { "randombytes": "^2.0.5", "safe-buffer": "^5.1.0" } }, "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw=="], + + "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], + + "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + + "real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + + "require-in-the-middle": ["require-in-the-middle@7.5.2", "", { "dependencies": { "debug": "^4.3.5", "module-details-from-path": "^1.0.3", "resolve": "^1.22.8" } }, "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ=="], + + "resolve": ["resolve@1.22.10", "", { "dependencies": { "is-core-module": "^2.16.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w=="], + + "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], + + "retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], + + "ripemd160": ["ripemd160@2.0.2", "", { "dependencies": { "hash-base": "^3.0.0", "inherits": "^2.0.1" } }, "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA=="], + + "rollup": ["rollup@4.40.2", "", { "dependencies": { "@types/estree": "1.0.7" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.40.2", "@rollup/rollup-android-arm64": "4.40.2", "@rollup/rollup-darwin-arm64": "4.40.2", "@rollup/rollup-darwin-x64": "4.40.2", "@rollup/rollup-freebsd-arm64": "4.40.2", "@rollup/rollup-freebsd-x64": "4.40.2", "@rollup/rollup-linux-arm-gnueabihf": "4.40.2", "@rollup/rollup-linux-arm-musleabihf": "4.40.2", "@rollup/rollup-linux-arm64-gnu": "4.40.2", "@rollup/rollup-linux-arm64-musl": "4.40.2", "@rollup/rollup-linux-loongarch64-gnu": "4.40.2", "@rollup/rollup-linux-powerpc64le-gnu": "4.40.2", "@rollup/rollup-linux-riscv64-gnu": "4.40.2", "@rollup/rollup-linux-riscv64-musl": "4.40.2", "@rollup/rollup-linux-s390x-gnu": "4.40.2", "@rollup/rollup-linux-x64-gnu": "4.40.2", "@rollup/rollup-linux-x64-musl": "4.40.2", "@rollup/rollup-win32-arm64-msvc": "4.40.2", "@rollup/rollup-win32-ia32-msvc": "4.40.2", "@rollup/rollup-win32-x64-msvc": "4.40.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-tfUOg6DTP4rhQ3VjOO6B4wyrJnGOX85requAXvqYTHsOgb2TFJdZ3aWpT8W2kPoypSGP7dZUyzxJ9ee4buM5Fg=="], + + "rpc-websockets": ["rpc-websockets@9.1.1", "", { "dependencies": { "@swc/helpers": "^0.5.11", "@types/uuid": "^8.3.4", "@types/ws": "^8.2.2", "buffer": "^6.0.3", "eventemitter3": "^5.0.1", "uuid": "^8.3.2", "ws": "^8.5.0" }, "optionalDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" } }, "sha512-1IXGM/TfPT6nfYMIXkJdzn+L4JEsmb0FL1O2OBjaH03V3yuUDdKFulGLMFG6ErV+8pZ5HVC0limve01RyO+saA=="], + + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + + "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], + + "secure-json-parse": ["secure-json-parse@2.7.0", "", {}, "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="], + + "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], + + "sha.js": ["sha.js@2.4.11", "", { "dependencies": { "inherits": "^2.0.1", "safe-buffer": "^5.0.1" }, "bin": { "sha.js": "./bin.js" } }, "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "shimmer": ["shimmer@1.2.1", "", {}, "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw=="], + + "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], + + "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + + "simple-wcswidth": ["simple-wcswidth@1.0.1", "", {}, "sha512-xMO/8eNREtaROt7tJvWJqHBDTMFN4eiQ5I4JRMuilwfnFcV5W9u7RUkueNkdw0jPqGMX36iCywelS5yilTuOxg=="], + + "sonic-boom": ["sonic-boom@4.2.0", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww=="], + + "source-map": ["source-map@0.8.0-beta.0", "", { "dependencies": { "whatwg-url": "^7.0.0" } }, "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], + + "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], + + "std-env": ["std-env@3.9.0", "", {}, "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw=="], + + "stream-browserify": ["stream-browserify@3.0.0", "", { "dependencies": { "inherits": "~2.0.4", "readable-stream": "^3.5.0" } }, "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA=="], + + "stream-chain": ["stream-chain@2.2.5", "", {}, "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA=="], + + "stream-json": ["stream-json@1.9.1", "", { "dependencies": { "stream-chain": "^2.2.5" } }, "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw=="], + + "string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], + + "string-width-cjs": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], + + "strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="], + + "strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="], + + "sucrase": ["sucrase@3.35.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "glob": "^10.3.10", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA=="], + + "superstruct": ["superstruct@2.0.2", "", {}, "sha512-uV+TFRZdXsqXTL2pRvujROjdZQ4RAlBUS5BTh9IGm+jTqQntYThciG/qu57Gs69yjnVUSqdxF9YLmSnpupBW9A=="], + + "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="], + + "text-encoding-utf-8": ["text-encoding-utf-8@1.0.2", "", {}, "sha512-8bw4MY9WjdsD2aMtO0OzOCY3pXGYNx2d2FfHRVUKkiCPDWjKuOlhLVASS+pD7VkLTVjW268LYJHwsnPFlBpbAg=="], + + "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], + + "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], + + "thread-stream": ["thread-stream@3.1.0", "", { "dependencies": { "real-require": "^0.2.0" } }, "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A=="], + + "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], + + "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], + + "tinyglobby": ["tinyglobby@0.2.13", "", { "dependencies": { "fdir": "^6.4.4", "picomatch": "^4.0.2" } }, "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw=="], + + "tinypool": ["tinypool@1.0.2", "", {}, "sha512-al6n+QEANGFOMf/dmUMsuS5/r9B06uwlyNjZZql/zv8J7ybHCgoihBNORZCY2mzUuAnomQa2JdhyHKzZxPCrFA=="], + + "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], + + "tinyspy": ["tinyspy@3.0.2", "", {}, "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q=="], + + "tr46": ["tr46@1.0.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA=="], + + "tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="], + + "ts-interface-checker": ["ts-interface-checker@0.1.13", "", {}, "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="], + + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "tsup": ["tsup@8.5.0", "", { "dependencies": { "bundle-require": "^5.1.0", "cac": "^6.7.14", "chokidar": "^4.0.3", "consola": "^3.4.0", "debug": "^4.4.0", "esbuild": "^0.25.0", "fix-dts-default-cjs-exports": "^1.0.0", "joycon": "^3.1.1", "picocolors": "^1.1.1", "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", "rollup": "^4.34.8", "source-map": "0.8.0-beta.0", "sucrase": "^3.35.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "peerDependencies": { "@microsoft/api-extractor": "^7.36.0", "@swc/core": "^1", "postcss": "^8.4.12", "typescript": ">=4.5.0" }, "optionalPeers": ["@microsoft/api-extractor", "@swc/core", "postcss", "typescript"], "bin": { "tsup": "dist/cli-default.js", "tsup-node": "dist/cli-node.js" } }, "sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ=="], + + "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], + + "ufo": ["ufo@1.6.1", "", {}, "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA=="], + + "uglify-js": ["uglify-js@3.19.3", "", { "bin": { "uglifyjs": "bin/uglifyjs" } }, "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ=="], + + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "unique-names-generator": ["unique-names-generator@4.7.1", "", {}, "sha512-lMx9dX+KRmG8sq6gulYYpKWZc9RlGsgBR6aoO8Qsm3qvkSJ+3rAymr+TnV8EDMrIrwuFJ4kruzMWM/OpYzPoow=="], + + "utf-8-validate": ["utf-8-validate@5.0.10", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ=="], + + "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + + "uuid": ["uuid@11.0.3", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg=="], + + "viem": ["viem@2.29.4", "", { "dependencies": { "@noble/curves": "1.8.2", "@noble/hashes": "1.7.2", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-Dhyae+w1LKKpYVXypGjBnZ3WU5EHl/Uip5RtVwVRYSVxD5VvHzqKzIfbFU1KP4vnnh3++ZNgLjBY/kVT/tPrrg=="], + + "vite": ["vite@6.3.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="], + + "vite-node": ["vite-node@3.1.3", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.0", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-uHV4plJ2IxCl4u1up1FQRrqclylKAogbtBfOTwcuJ28xFi+89PZ57BRh+naIRvH70HPwxy5QHYzg1OrEaC7AbA=="], + + "vitest": ["vitest@3.1.3", "", { "dependencies": { "@vitest/expect": "3.1.3", "@vitest/mocker": "3.1.3", "@vitest/pretty-format": "^3.1.3", "@vitest/runner": "3.1.3", "@vitest/snapshot": "3.1.3", "@vitest/spy": "3.1.3", "@vitest/utils": "3.1.3", "chai": "^5.2.0", "debug": "^4.4.0", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.13", "tinypool": "^1.0.2", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0", "vite-node": "3.1.3", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.1.3", "@vitest/ui": "3.1.3", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-188iM4hAHQ0km23TN/adso1q5hhwKqUpv+Sd6p5sOuh6FhQnRNW3IsiIpvxqahtBabsJ2SLZgmGSpcYK4wQYJw=="], + + "web-streams-polyfill": ["web-streams-polyfill@4.0.0-beta.3", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="], + + "webidl-conversions": ["webidl-conversions@4.0.2", "", {}, "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg=="], + + "whatwg-url": ["whatwg-url@7.1.0", "", { "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], + + "wordwrap": ["wordwrap@1.0.0", "", {}, "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q=="], + + "wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="], + + "wrap-ansi-cjs": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "ws": ["ws@8.18.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w=="], + + "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], + + "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], + + "yaml": ["yaml@2.8.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ=="], + + "yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], + + "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], + + "zod": ["zod@3.24.4", "", {}, "sha512-OdqJE9UDRPwWsrHjLN2F8bPxvwJBK22EHLWtanu0LSYr5YqzsaaW3RMgmjwr8Rypg5k+meEJdSPXJZXE/yqOMg=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.24.5", "", { "peerDependencies": { "zod": "^3.24.1" } }, "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g=="], + + "@langchain/core/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], + + "@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], + + "@opentelemetry/exporter-zipkin/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], + + "@opentelemetry/instrumentation/@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.200.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-IKJBQxh91qJ+3ssRly5hYEJ8NDHu9oY/B1PXVSCWf7zytmYO9RNLB0Ox9XQ/fJ8m6gY6Q6NtBWlmXfaXt5Uc4Q=="], + + "@opentelemetry/instrumentation-pg/@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], + + "@opentelemetry/otlp-transformer/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0SvDXmou/JjzSDOjUmetAAvcKQW6ZrvosU0rkbDGpXvvZN+pQF6JbK/Kd4hNdK4q/22yeruqvukXEJyySTzyTQ=="], + + "@opentelemetry/resources/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], + + "@opentelemetry/sdk-metrics/@opentelemetry/core": ["@opentelemetry/core@1.30.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "1.28.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ=="], + + "@opentelemetry/sdk-metrics/@opentelemetry/resources": ["@opentelemetry/resources@1.30.1", "", { "dependencies": { "@opentelemetry/core": "1.30.1", "@opentelemetry/semantic-conventions": "1.28.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA=="], + + "@opentelemetry/sdk-node/@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "semver": "^7.5.2", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-DMwg0hy4wzf7K73JJtl95m/e0boSoWhH07rfvHvYzQtBD3Bmv0Wc1x733vyZBqmFm8OjJD0/pfiUg1W3JjFX0A=="], + + "@opentelemetry/sdk-node/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0SvDXmou/JjzSDOjUmetAAvcKQW6ZrvosU0rkbDGpXvvZN+pQF6JbK/Kd4hNdK4q/22yeruqvukXEJyySTzyTQ=="], + + "@opentelemetry/sdk-node/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], + + "@opentelemetry/sdk-trace-base/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], + + "@opentelemetry/sql-common/@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], + + "@phala/dstack-sdk/@solana/web3.js": ["@solana/web3.js@1.98.0", "", { "dependencies": { "@babel/runtime": "^7.25.0", "@noble/curves": "^1.4.2", "@noble/hashes": "^1.4.0", "@solana/buffer-layout": "^4.0.1", "agentkeepalive": "^4.5.0", "bigint-buffer": "^1.1.5", "bn.js": "^5.2.1", "borsh": "^0.7.0", "bs58": "^4.0.1", "buffer": "6.0.3", "fast-stable-stringify": "^1.0.0", "jayson": "^4.1.1", "node-fetch": "^2.7.0", "rpc-websockets": "^9.0.2", "superstruct": "^2.0.2" } }, "sha512-nz3Q5OeyGFpFCR+erX2f6JPt3sKhzhYcSycBCSPkWjzSVDh/Rr1FqTVMRe58FKO16/ivTUcuJjeS5MyBvpkbzA=="], + + "@phala/dstack-sdk/viem": ["viem@2.23.11", "", { "dependencies": { "@noble/curves": "1.8.1", "@noble/hashes": "1.7.1", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.6", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-yPkHJt4Vn88kLlrv8mrtVN54PW4vNLWRWDScf8SaHK2f44VlMk5IZbMJw4ycUoW9K9GUvCMrYuUa34MAcwYHIg=="], + + "@scure/bip32/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], + + "@scure/bip32/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + + "@scure/bip39/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + + "@solana/errors/chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="], + + "@solana/errors/commander": ["commander@13.1.0", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="], + + "asn1.js/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "browserify-sign/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], + + "chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "cliui/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "create-ecdh/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "diffie-hellman/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "elliptic/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "handlebars/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + + "jayson/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="], + + "jayson/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], + + "jayson/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + + "jayson/ws": ["ws@7.5.10", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ=="], + + "langchain/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], + + "langsmith/@types/uuid": ["@types/uuid@10.0.0", "", {}, "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="], + + "langsmith/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], + + "miller-rabin/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + + "openai/@types/node": ["@types/node@18.19.100", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-ojmMP8SZBKprc3qGrGk8Ujpo80AXkrP7G2tOT4VWr5jlr5DHjsJF+emXJz+Wm0glmy4Js62oKMdZZ6B9Y+tEcA=="], + + "p-queue/eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="], + + "public-encrypt/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], + + "rpc-websockets/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], + + "rpc-websockets/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + + "string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "string-width-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "strip-ansi-cjs/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "sucrase/glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="], + + "viem/@noble/curves": ["@noble/curves@1.8.2", "", { "dependencies": { "@noble/hashes": "1.7.2" } }, "sha512-vnI7V6lFNe0tLAuJMu+2sX+FcL14TaCWy1qiczg1VwRmPrpQCdq5ESXQMqUc2tluRNf6irBXrWbl1mGN8uaU/g=="], + + "viem/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], + + "wrap-ansi/ansi-styles": ["ansi-styles@6.2.1", "", {}, "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug=="], + + "wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "wrap-ansi-cjs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "wrap-ansi-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "@opentelemetry/instrumentation-pg/@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], + + "@opentelemetry/sql-common/@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], + + "@phala/dstack-sdk/viem/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], + + "@phala/dstack-sdk/viem/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + + "@phala/dstack-sdk/viem/isows": ["isows@1.0.6", "", { "peerDependencies": { "ws": "*" } }, "sha512-lPHCayd40oW98/I0uvgaHKWCSvkzY27LjWLbtzOm64yQ+G3Q5npjjbdppU65iZXkK1Zt+kH9pfegli0AYfwYYw=="], + + "browserify-sign/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], + + "browserify-sign/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], + + "cliui/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "node-fetch/whatwg-url/tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + + "node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + + "openai/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], + + "string-width-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "sucrase/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], + + "sucrase/glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], + + "sucrase/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], + + "wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "wrap-ansi-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "sucrase/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], + + "yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + } +} diff --git a/bun.lockb b/bun.lockb deleted file mode 100755 index d28065ecd38341e67f05c4fc7a1b3e999bfc9269..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 164895 zcmeFac|4U}7w~@+Atf4AqB3WmWr)l)%20+P(=lbrkVK_HqB0Z}ku$%_i&cXZ7@ArB3=f147_g>$%)*i2YUFY;XVj_y6!9j|y-u{Yo z|5ejnL;Xj>CGQ*Hw!*{PmoD!S5aj0)BEL#$Ei-kx|TiMmkfWFF%e(i(2JP_ruIpxJE-h zhbgl_j>38XctEBw^DeI5A>n~^ns;zOSTL0J{Q()U8va0f4}qYazuT*Yaseo}0i7`* z)7fdX2_R#b(lyk>gC0bqdDH3ind)k^4IDHYH`IqiJuk?8z@t1gf+3S2KN9j*kjFSf zf_=SR!L}LXF`%wP%kvp+Z~E%E0}g|KneBzurZJvndOT>Vmn}f+`auh zgExRPKFFIuIqK_xME};1L7572EXa@`H4U`m;}RYm;Qv?uTma|D$%0Xg;~@OO{!amk ze(2%!z6iE5^Wo4~)OV-*x`czh^-zxO`Fp#(pd9aXB~j*Q^qhdc(0{z<=_ght>vrGdoyEHH-S#Xg?l=PTsVpSQmkJ;*yG zI05v~?j{&a^cxNm`(rv7fzYD7AdhweL;V8573~d_qrU)uH#+9Sf?NUvp@Ej5HxbH% z1AVfBbjM4*%?b!nDLc4BL8TEF;jPYF);ErZ#q`v~? zgXkea;k29681@-C8ZA(MWhgzA{-5;_Je^_hJ5&0F28Xz~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*X9%BEGJfDVerWuen!cZ15Pj=%?voE5^THL2sigYKZ1TqXv6ANqJy zfIq$H(21o?e$}hQJD~FQ8gEytTPn1d}PMdB^Spz!U$Wm#9vDF3o}2ky#APpPvC zL6S)k?P8UjBCR!R^ z$_xT5*Fc!%n9Ye?*+N{+Bt0xko3wPmjo)bq&VTh;Mgjf`$l#AK9ip$Avr)J}RB7Xt z1{&4{TT;Z4wxcu$SJD7Y;FfxfZKCu#tCnWDP)LOQNmg67PhT~&x%OZsv z+y9tttXi%`k}$$ei7XZwERxt+ipnMg9*Za;Aw|;o;ARoVpQlI`-(ES>rJ%iXjDlxN z&Qhce<%a+X3lLa78v?ED91i4$F@B%Y*9ilC6RyZu2)!kCe3v68bC z$`Mo&B&Ebg5?&Zda`vM-38Na4A{>9842@hz#p;u9IkHRsw4DKT2uzH@rM{M z^Y18;>Fww_Z`^jJ``f}H_-OBf{QX6|x{R{IGxz~m1jeR8`OB^EmV?te0mEee#tS{+ vpfsCY4{oK`L7o*K8Cu){$v!Kn)fm0xUxp=I24TV>EKiSYp=gT#(7*o&)xYu4 diff --git a/dist/index.js b/dist/index.js index 257dbbb..ddaca04 100644 --- a/dist/index.js +++ b/dist/index.js @@ -12,9 +12,15 @@ var TeeVendorNames = { import { logger as logger2 } from "@elizaos/core"; // src/providers/remoteAttestationProvider.ts -import { logger } from "@elizaos/core"; -import { TEEMode } from "@elizaos/core"; -import { TappdClient } from "@phala/dstack-sdk"; +import { + logger +} from "@elizaos/core"; +import { + TEEMode +} from "@elizaos/core"; +import { + TappdClient +} from "@phala/dstack-sdk"; // src/providers/base.ts var DeriveKeyProvider = class { @@ -35,26 +41,35 @@ var PhalaRemoteAttestationProvider = class extends RemoteAttestationProvider { break; case TEEMode.DOCKER: endpoint = "http://host.docker.internal:8090"; - logger.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090"); + logger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); break; case TEEMode.PRODUCTION: endpoint = void 0; logger.log("TEE: Running in production mode without simulator"); break; default: - throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); } this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); } async generateAttestation(reportData, hashAlgorithm) { try { logger.log("Generating attestation for: ", reportData); - const tdxQuote = await this.client.tdxQuote(reportData, hashAlgorithm); + const tdxQuote = await this.client.tdxQuote( + reportData, + hashAlgorithm + ); const rtmrs = tdxQuote.replayRtmrs(); - logger.log(`rtmr0: ${rtmrs[0]} + logger.log( + `rtmr0: ${rtmrs[0]} rtmr1: ${rtmrs[1]} rtmr2: ${rtmrs[2]} -rtmr3: ${rtmrs[3]}f`); +rtmr3: ${rtmrs[3]}f` + ); const quote = { quote: tdxQuote.quote, timestamp: Date.now() @@ -82,11 +97,16 @@ var phalaRemoteAttestationProvider = { message: { entityId: message.entityId, roomId: message.roomId, - content: message.content.text + content: message.content.text || "" } }; - logger.log("Generating attestation for: ", JSON.stringify(attestationMessage)); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + logger.log( + "Generating attestation for: ", + JSON.stringify(attestationMessage) + ); + const attestation = await provider.generateAttestation( + JSON.stringify(attestationMessage) + ); return { text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`, data: { @@ -107,6 +127,7 @@ var phalaRemoteAttestationProvider = { }; // src/utils.ts +import { createHash } from "crypto"; function hexToUint8Array(hex) { const hexString = hex.trim().replace(/^0x/, ""); if (!hexString) { @@ -155,18 +176,22 @@ var phalaRemoteAttestationAction = { message: { entityId: message.entityId, roomId: message.roomId, - content: message.content.text + content: message.content.text || "" } }; const teeMode = runtime.getSetting("TEE_MODE"); logger2.debug(`Tee mode: ${teeMode}`); - logger2.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`); + logger2.debug( + `Attestation message: ${JSON.stringify(attestationMessage)}` + ); const provider = new PhalaRemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + const attestation = await provider.generateAttestation( + JSON.stringify(attestationMessage) + ); const attestationData = hexToUint8Array(attestation.quote); const response = await uploadUint8Array(attestationData); const data = await response.json(); - callback({ + callback?.({ text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} https://proof.t16z.com/reports/${data.checksum}`, actions: ["NONE"] @@ -230,8 +255,12 @@ https://proof.t16z.com/reports/${data.checksum}`, }; // src/providers/deriveKeyProvider.ts -import { logger as logger3 } from "@elizaos/core"; -import { TEEMode as TEEMode2 } from "@elizaos/core"; +import { + logger as logger3 +} from "@elizaos/core"; +import { + TEEMode as TEEMode2 +} from "@elizaos/core"; import { TappdClient as TappdClient2 } from "@phala/dstack-sdk"; import { toViemAccount } from "@phala/dstack-sdk/viem"; import { toKeypair } from "@phala/dstack-sdk/solana"; @@ -248,14 +277,18 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider { break; case TEEMode2.DOCKER: endpoint = "http://host.docker.internal:8090"; - logger3.log("TEE: Connecting to simulator via Docker at host.docker.internal:8090"); + logger3.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); break; case TEEMode2.PRODUCTION: endpoint = void 0; logger3.log("TEE: Running in production mode without simulator"); break; default: - throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); } this.client = endpoint ? new TappdClient2(endpoint) : new TappdClient2(); this.raProvider = new PhalaRemoteAttestationProvider(teeMode); @@ -331,9 +364,17 @@ var PhalaDeriveKeyProvider = class extends DeriveKeyProvider { logger3.error("Path and Subject are required for key derivation"); } logger3.log("Deriving ECDSA Key in TEE..."); - const deriveKeyResponse = await this.client.deriveKey(path, subject); - const keypair = toViemAccount(deriveKeyResponse); - const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address); + const deriveKeyResponse = await this.client.deriveKey( + path, + subject + ); + const keypair = toViemAccount( + deriveKeyResponse + ); + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.address + ); logger3.log("ECDSA Key Derived Successfully!"); return { keypair, attestation }; } catch (error) { @@ -359,8 +400,16 @@ var phalaDeriveKeyProvider = { } try { const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; - const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, "solana", agentId); - const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, "evm", agentId); + const solanaKeypair = await provider.deriveEd25519Keypair( + secretSalt, + "solana", + agentId + ); + const evmKeypair = await provider.deriveEcdsaKeypair( + secretSalt, + "evm", + agentId + ); const walletData = { solana: solanaKeypair.keypair.publicKey, evm: evmKeypair.keypair.address @@ -385,11 +434,12 @@ EVM Address: ${values.evm_address}`; }; } } catch (error) { - logger3.error("Error in derive key provider:", error.message); + const errorMessage = error instanceof Error ? error.message : "Unknown error"; + logger3.error("Error in derive key provider:", errorMessage); return { data: null, values: {}, - text: `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}` + text: `Failed to fetch derive key information: ${errorMessage}` }; } } diff --git a/dist/index.js.map b/dist/index.js.map index ee0cdf0..36675b0 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/vendors/types.ts","../src/actions/remoteAttestationAction.ts","../src/providers/remoteAttestationProvider.ts","../src/providers/base.ts","../src/utils.ts","../src/providers/deriveKeyProvider.ts","../src/vendors/phala.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Plugin,\n type TeePluginConfig,\n type TeeVendorConfig,\n logger,\n} from '@elizaos/core';\nimport { TeeVendorNames } from './vendors/types';\nimport { getVendor } from './vendors/index';\n\nexport { phalaRemoteAttestationAction } from './actions/remoteAttestationAction';\nexport { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider';\nexport { PhalaRemoteAttestationProvider } from './providers/remoteAttestationProvider';\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(config: Record, runtime: IAgentRuntime) {\n if (config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR')) {\n const vendor = config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR');\n logger.info(`Initializing TEE with vendor: ${vendor}`);\n let plugin: Plugin;\n switch (vendor) {\n case 'phala':\n plugin = teePlugin({\n vendor: TeeVendorNames.PHALA,\n });\n break;\n default:\n throw new Error(`Invalid TEE vendor: ${vendor}`);\n }\n logger.info(`Pushing plugin: ${plugin.name}`);\n runtime.plugins.push(plugin);\n }\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n const vendorType = config?.vendor || TeeVendorNames.PHALA;\n const vendor = getVendor(vendorType);\n return {\n name: vendor.getName(),\n init: async (config: Record, runtime: IAgentRuntime) => {\n return await initializeTEE(\n {\n ...config,\n vendor: vendorType,\n },\n runtime\n );\n },\n description: vendor.getDescription(),\n actions: vendor.getActions(),\n evaluators: [],\n providers: vendor.getProviders(),\n services: [],\n };\n};\n","import type { Action, Provider } from '@elizaos/core';\n\nexport const TeeVendorNames = {\n PHALA: 'phala',\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName = (typeof TeeVendorNames)[keyof typeof TeeVendorNames] | string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n type: TeeVendorName;\n getActions(): Action[];\n getProviders(): Provider[];\n getName(): string;\n getDescription(): string;\n}\n","import type {\n HandlerCallback,\n IAgentRuntime,\n Memory,\n RemoteAttestationMessage,\n State,\n} from '@elizaos/core';\nimport { logger } from '@elizaos/core';\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from '../providers/remoteAttestationProvider';\nimport { hexToUint8Array } from '../utils';\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: 'application/octet-stream' });\n const formData = new FormData();\n formData.append('file', blob, 'quote.bin');\n\n return await fetch('https://proof.t16z.com/api/upload', {\n method: 'POST',\n body: formData as BodyInit,\n });\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}}\n */\nexport const phalaRemoteAttestationAction = {\n name: 'REMOTE_ATTESTATION',\n similes: [\n 'REMOTE_ATTESTATION',\n 'TEE_REMOTE_ATTESTATION',\n 'TEE_ATTESTATION',\n 'TEE_QUOTE',\n 'ATTESTATION',\n 'TEE_ATTESTATION_QUOTE',\n ],\n description: 'Generate a remote attestation to prove that the agent is running in a TEE',\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State,\n _options: { [key: string]: unknown },\n callback: HandlerCallback\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting('TEE_MODE');\n logger.debug(`Tee mode: ${teeMode}`);\n logger.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`);\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n\n callback({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n actions: ['NONE'],\n });\n return true;\n } catch (error) {\n console.error('Failed to fetch remote attestation: ', error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n name: '{{name1}}',\n content: {\n text: 'If you are running in a TEE, generate a remote attestation',\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'Of course, one second...',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n [\n {\n name: '{{name1}}',\n content: {\n text: 'Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?',\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n [\n {\n name: '{{name1}}',\n content: {\n text: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n },\n },\n {\n name: '{{agentName}}',\n content: {\n text: 'Oh, dear...lemme find that for you',\n actions: ['REMOTE_ATTESTATION'],\n },\n },\n ],\n ],\n};\n","import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core';\nimport { type RemoteAttestationMessage, type RemoteAttestationQuote, TEEMode } from '@elizaos/core';\nimport { TappdClient, type TdxQuoteHashAlgorithms, type TdxQuoteResponse } from '@phala/dstack-sdk';\nimport { RemoteAttestationProvider } from './base';\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = 'http://localhost:8090';\n logger.log('TEE: Connecting to local simulator at localhost:8090');\n break;\n case TEEMode.DOCKER:\n endpoint = 'http://host.docker.internal:8090';\n logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090');\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log('TEE: Running in production mode without simulator');\n break;\n default:\n throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`);\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n logger.log('Generating attestation for: ', reportData);\n const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(reportData, hashAlgorithm);\n const rtmrs = tdxQuote.replayRtmrs();\n logger.log(`rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`);\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n logger.log('Remote attestation quote: ', quote);\n return quote;\n } catch (error) {\n console.error('Error generating remote attestation:', error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n name: 'phala-remote-attestation',\n get: async (runtime: IAgentRuntime, message: Memory) => {\n const teeMode = runtime.getSetting('TEE_MODE');\n const provider = new PhalaRemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text,\n },\n };\n logger.log('Generating attestation for: ', JSON.stringify(attestationMessage));\n const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage));\n return {\n text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`,\n data: {\n attestation,\n },\n values: {\n quote: attestation.quote,\n timestamp: attestation.timestamp.toString(),\n },\n };\n } catch (error) {\n console.error('Error in remote attestation provider:', error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n },\n};\n\nexport { phalaRemoteAttestationProvider, PhalaRemoteAttestationProvider };\n","import type { RemoteAttestationQuote } from '@elizaos/core';\nimport type { TdxQuoteHashAlgorithms } from '@phala/dstack-sdk';\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n abstract generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise;\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n const hexString = hex.trim().replace(/^0x/, '');\n if (!hexString) {\n throw new Error('Invalid hex string');\n }\n if (hexString.length % 2 !== 0) {\n throw new Error('Invalid hex string');\n }\n\n const array = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n const byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error('Invalid hex string');\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n const hash = createHash('sha256');\n hash.update(input);\n return hash.digest();\n}\n","import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core';\nimport { type DeriveKeyAttestationData, type RemoteAttestationQuote, TEEMode } from '@elizaos/core';\nimport { type DeriveKeyResponse, TappdClient } from '@phala/dstack-sdk';\nimport { Keypair } from '@solana/web3.js';\nimport { toViemAccount } from '@phala/dstack-sdk/viem';\nimport { toKeypair } from '@phala/dstack-sdk/solana';\nimport { DeriveKeyProvider } from './base';\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from './remoteAttestationProvider';\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = 'http://localhost:8090';\n logger.log('TEE: Connecting to local simulator at localhost:8090');\n break;\n case TEEMode.DOCKER:\n endpoint = 'http://host.docker.internal:8090';\n logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090');\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log('TEE: Running in production mode without simulator');\n break;\n default:\n throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`);\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n logger.log('Generating Remote Attestation Quote for Derive Key...');\n const quote = await this.raProvider.generateAttestation(reportdata);\n logger.log('Remote Attestation Quote generated successfully!');\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(path: string, subject: string): Promise {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving Raw Key in TEE...');\n const derivedKey = await this.client.deriveKey(path, subject);\n\n logger.log('Raw Key Derived Successfully!');\n return derivedKey;\n } catch (error) {\n logger.error('Error deriving raw key:', error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving Key in TEE...');\n const derivedKey = await this.client.deriveKey(path, subject);\n const keypair = toKeypair(derivedKey);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n logger.log('Key Derived Successfully!');\n\n return { keypair, attestation };\n } catch (error) {\n logger.error('Error deriving key:', error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n logger.error('Path and Subject are required for key derivation');\n }\n\n logger.log('Deriving ECDSA Key in TEE...');\n const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(path, subject);\n const keypair = toViemAccount(deriveKeyResponse);\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address);\n logger.log('ECDSA Key Derived Successfully!');\n\n return { keypair, attestation };\n } catch (error) {\n logger.error('Error deriving ecdsa key:', error);\n throw error;\n }\n }\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n name: 'phala-derive-key',\n get: async (runtime: IAgentRuntime, _message?: Memory): Promise => {\n const teeMode = runtime.getSetting('TEE_MODE');\n const provider = new PhalaDeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting('WALLET_SECRET_SALT')) {\n logger.error('Wallet secret salt is not configured in settings');\n return {\n data: null,\n values: {},\n text: 'Wallet secret salt is not configured in settings',\n };\n }\n\n try {\n const secretSalt = runtime.getSetting('WALLET_SECRET_SALT') || 'secret_salt';\n const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, 'solana', agentId);\n const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, 'evm', agentId);\n\n // Original data structure\n const walletData = {\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n };\n\n // Values for template injection\n const values = {\n solana_public_key: solanaKeypair.keypair.publicKey.toString(),\n evm_address: evmKeypair.keypair.address,\n };\n\n // Text representation\n const text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n return {\n data: walletData,\n values: values,\n text: text,\n };\n } catch (error) {\n logger.error('Error creating PublicKey:', error);\n return {\n data: null,\n values: {},\n text: `Error creating PublicKey: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n };\n }\n } catch (error) {\n logger.error('Error in derive key provider:', error.message);\n return {\n data: null,\n values: {},\n text: `Failed to fetch derive key information: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n };\n }\n },\n};\n\nexport { phalaDeriveKeyProvider, PhalaDeriveKeyProvider };\n","import { phalaRemoteAttestationAction as remoteAttestationAction } from '../actions/remoteAttestationAction';\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from '../providers/deriveKeyProvider';\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from '../providers/remoteAttestationProvider';\nimport { type TeeVendor, TeeVendorNames } from './types';\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendorNames.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n type = TeeVendorNames.PHALA;\n\n /**\n * Returns an array of actions.\n *\n * @returns {Array} An array containing the remote attestation action.\n */\n getActions() {\n return [remoteAttestationAction];\n }\n /**\n * Retrieve the list of providers.\n *\n * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n */\n getProviders() {\n return [deriveKeyProvider, remoteAttestationProvider];\n }\n\n /**\n * Returns the name of the plugin.\n * @returns {string} The name of the plugin.\n */\n getName() {\n return 'phala-tee-plugin';\n }\n\n /**\n * Get the description of the function\n * @returns {string} The description of the function\n */\n getDescription() {\n return 'Phala TEE Cloud to Host Eliza Agents';\n }\n}\n","import { PhalaVendor } from './phala';\nimport type { TeeVendor } from './types';\nimport { type TeeVendorName, TeeVendorNames } from './types';\n\nconst vendors: Record = {\n [TeeVendorNames.PHALA]: new PhalaVendor(),\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n const vendor = vendors[type];\n if (!vendor) {\n throw new Error(`Unsupported TEE vendor type: ${type}`);\n }\n return vendor;\n};\n\nexport * from './types';\n"],"mappings":";AAAA;AAAA,EAKE,UAAAA;AAAA,OACK;;;ACJA,IAAM,iBAAiB;AAAA,EAC5B,OAAO;AACT;;;ACGA,SAAS,UAAAC,eAAc;;;ACPvB,SAAyD,cAAc;AACvE,SAAqE,eAAe;AACpF,SAAS,mBAAuE;;;ACuBzE,IAAe,oBAAf,MAAiC;AAAC;AAKlC,IAAe,4BAAf,MAAyC;AAKhD;;;ADLA,IAAM,iCAAN,cAA6C,0BAA0B;AAAA,EAC7D;AAAA,EAER,YAAY,SAAkB;AAC5B,UAAM;AACN,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACf,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO,IAAI,sDAAsD;AACjE;AAAA,MACF,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO,IAAI,sEAAsE;A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AG;AACzD,UAAM,SAAS,OAAO,cAAc,QAAQ,WAAW,YAAY;AACnE,IAAAE,QAAO,KAAK,iCAAiC,MAAM,EAAE;AACrD,QAAI;AACJ,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,iBAAS,UAAU;AAAA,UACjB,QAAQ,eAAe;AAAA,QACzB,CAAC;AACD;AAAA,MACF;AACE,cAAM,IAAI,MAAM,uBAAuB,MAAM,EAAE;AAAA,IACnD;AACA,IAAAA,QAAO,KAAK,mBAAmB,OAAO,IAAI,EAAE;AAC5C,YAAQ,QAAQ,KAAK,MAAM;AAAA,EAC7B;AACF;AAOO,IAAM,YAAY,CAAC,WAAqC;AAC7D,QAAM,aAAa,QAAQ,UAAU,eAAe;AACpD,QAAM,SAAS,UAAU,UAAU;AACnC,SAAO;AAAA,IACL,MAAM,OAAO,QAAQ;AAAA,IACrB,MAAM,OAAOC,SAAgC,YAA2B;AACtE,aAAO,MAAM;AAAA,QACX;AAAA,UACE,GAAGA;AAAA,UACH,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,aAAa,OAAO,eAAe;AAAA,IACnC,SAAS,OAAO,WAAW;AAAA,IAC3B,YAAY,CAAC;AAAA,IACb,WAAW,OAAO,aAAa;AAAA,IAC/B,UAAU,CAAC;AAAA,EACb;AACF;","names":["logger","logger","logger","logger","TEEMode","TappdClient","TEEMode","logger","TappdClient","logger","config"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/vendors/types.ts","../src/actions/remoteAttestationAction.ts","../src/providers/remoteAttestationProvider.ts","../src/providers/base.ts","../src/utils.ts","../src/providers/deriveKeyProvider.ts","../src/vendors/phala.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Plugin,\n type TeePluginConfig,\n type TeeVendorConfig,\n logger,\n} from \"@elizaos/core\";\nimport { TeeVendorNames } from \"./vendors/types\";\nimport { getVendor } from \"./vendors/index\";\n\nexport { phalaRemoteAttestationAction } from \"./actions/remoteAttestationAction\";\nexport { PhalaDeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { PhalaRemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(\n config: Record,\n runtime: IAgentRuntime\n) {\n if (config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\")) {\n const vendor = config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\");\n logger.info(`Initializing TEE with vendor: ${vendor}`);\n let plugin: Plugin;\n switch (vendor) {\n case \"phala\":\n plugin = teePlugin({\n vendor: TeeVendorNames.PHALA,\n });\n break;\n default:\n throw new Error(`Invalid TEE vendor: ${vendor}`);\n }\n logger.info(`Pushing plugin: ${plugin.name}`);\n runtime.plugins.push(plugin);\n }\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n const vendorType = config?.vendor || TeeVendorNames.PHALA;\n const vendor = getVendor(vendorType);\n return {\n name: vendor.getName(),\n init: async (config: Record, runtime: IAgentRuntime) => {\n return await initializeTEE(\n {\n ...config,\n vendor: vendorType,\n },\n runtime\n );\n },\n description: vendor.getDescription(),\n actions: vendor.getActions(),\n evaluators: [],\n providers: vendor.getProviders(),\n services: [],\n };\n};\n","import type { Action, Provider } from \"@elizaos/core\";\n\nexport const TeeVendorNames = {\n PHALA: \"phala\",\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName =\n | (typeof TeeVendorNames)[keyof typeof TeeVendorNames]\n | string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n type: TeeVendorName;\n getActions(): Action[];\n getProviders(): Provider[];\n getName(): string;\n getDescription(): string;\n}\n","import type {\n HandlerCallback,\n IAgentRuntime,\n Memory,\n RemoteAttestationMessage,\n State,\n} from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { hexToUint8Array } from \"../utils\";\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, \"quote.bin\");\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}}\n */\nexport const phalaRemoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\n \"REMOTE_ATTESTATION\",\n \"TEE_REMOTE_ATTESTATION\",\n \"TEE_ATTESTATION\",\n \"TEE_QUOTE\",\n \"ATTESTATION\",\n \"TEE_ATTESTATION_QUOTE\",\n ],\n description:\n \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state?: State,\n _options?: { [key: string]: unknown },\n callback?: HandlerCallback\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text || \"\",\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n logger.debug(`Tee mode: ${teeMode}`);\n logger.debug(\n `Attestation message: ${JSON.stringify(attestationMessage)}`\n );\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(\n JSON.stringify(attestationMessage)\n );\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n\n callback?.({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n actions: [\"NONE\"],\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"Of course, one second...\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"Oh, dear...lemme find that for you\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n ],\n};\n","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n logger,\n} from \"@elizaos/core\";\nimport {\n type RemoteAttestationMessage,\n type RemoteAttestationQuote,\n TEEMode,\n} from \"@elizaos/core\";\nimport {\n TappdClient,\n type TdxQuoteHashAlgorithms,\n type TdxQuoteResponse,\n} from \"@phala/dstack-sdk\";\nimport { RemoteAttestationProvider } from \"./base\";\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n logger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n logger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log(\"TEE: Running in production mode without simulator\");\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n logger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(\n reportData,\n hashAlgorithm\n );\n const rtmrs = tdxQuote.replayRtmrs();\n logger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n logger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n name: \"phala-remote-attestation\",\n get: async (runtime: IAgentRuntime, message: Memory) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new PhalaRemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text || \"\",\n },\n };\n logger.log(\n \"Generating attestation for: \",\n JSON.stringify(attestationMessage)\n );\n const attestation = await provider.generateAttestation(\n JSON.stringify(attestationMessage)\n );\n return {\n text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`,\n data: {\n attestation,\n },\n values: {\n quote: attestation.quote,\n timestamp: attestation.timestamp.toString(),\n },\n };\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n },\n};\n\nexport { phalaRemoteAttestationProvider, PhalaRemoteAttestationProvider };\n","import type { RemoteAttestationQuote } from \"@elizaos/core\";\nimport type { TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n abstract generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise;\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n const hexString = hex.trim().replace(/^0x/, \"\");\n if (!hexString) {\n throw new Error(\"Invalid hex string\");\n }\n if (hexString.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n const byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n const hash = createHash(\"sha256\");\n hash.update(input);\n return hash.digest();\n}\n","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n logger,\n} from \"@elizaos/core\";\nimport {\n type DeriveKeyAttestationData,\n type RemoteAttestationQuote,\n TEEMode,\n} from \"@elizaos/core\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { Keypair } from \"@solana/web3.js\";\nimport { toViemAccount } from \"@phala/dstack-sdk/viem\";\nimport { toKeypair } from \"@phala/dstack-sdk/solana\";\nimport { DeriveKeyProvider } from \"./base\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { PrivateKeyAccount } from \"viem\";\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n logger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n logger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log(\"TEE: Running in production mode without simulator\");\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n logger.log(\"Generating Remote Attestation Quote for Derive Key...\");\n const quote = await this.raProvider.generateAttestation(reportdata);\n logger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n logger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n logger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const keypair = toKeypair(derivedKey) as unknown as Keypair;\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n logger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n logger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(\n path,\n subject\n );\n const keypair = toViemAccount(\n deriveKeyResponse\n ) as unknown as PrivateKeyAccount;\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n logger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n logger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n name: \"phala-derive-key\",\n get: async (\n runtime: IAgentRuntime,\n _message?: Memory\n ): Promise => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new PhalaDeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n logger.error(\"Wallet secret salt is not configured in settings\");\n return {\n data: null,\n values: {},\n text: \"Wallet secret salt is not configured in settings\",\n };\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n secretSalt,\n \"solana\",\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n secretSalt,\n \"evm\",\n agentId\n );\n\n // Original data structure\n const walletData = {\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n };\n\n // Values for template injection\n const values = {\n solana_public_key: solanaKeypair.keypair.publicKey.toString(),\n evm_address: evmKeypair.keypair.address,\n };\n\n // Text representation\n const text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n return {\n data: walletData,\n values: values,\n text: text,\n };\n } catch (error) {\n logger.error(\"Error creating PublicKey:\", error);\n return {\n data: null,\n values: {},\n text: `Error creating PublicKey: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n };\n }\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Error in derive key provider:\", errorMessage);\n return {\n data: null,\n values: {},\n text: `Failed to fetch derive key information: ${errorMessage}`,\n };\n }\n },\n};\n\nexport { phalaDeriveKeyProvider, PhalaDeriveKeyProvider };\n","import { phalaRemoteAttestationAction as remoteAttestationAction } from \"../actions/remoteAttestationAction\";\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from \"../providers/deriveKeyProvider\";\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { type TeeVendor, TeeVendorNames } from \"./types\";\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendorNames.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n type = TeeVendorNames.PHALA;\n\n /**\n * Returns an array of actions.\n *\n * @returns {Array} An array containing the remote attestation action.\n */\n getActions() {\n return [remoteAttestationAction];\n }\n /**\n * Retrieve the list of providers.\n *\n * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n */\n getProviders() {\n return [deriveKeyProvider, remoteAttestationProvider];\n }\n\n /**\n * Returns the name of the plugin.\n * @returns {string} The name of the plugin.\n */\n getName() {\n return \"phala-tee-plugin\";\n }\n\n /**\n * Get the description of the function\n * @returns {string} The description of the function\n */\n getDescription() {\n return \"Phala TEE Cloud to Host Eliza Agents\";\n }\n}\n","import { PhalaVendor } from \"./phala\";\nimport type { TeeVendor } from \"./types\";\nimport { type TeeVendorName, TeeVendorNames } from \"./types\";\n\nconst vendors: Record = {\n [TeeVendorNames.PHALA]: new PhalaVendor() as TeeVendor,\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n const vendor = vendors[type];\n if (!vendor) {\n throw new Error(`Unsupported TEE vendor type: ${type}`);\n }\n return vendor;\n};\n\nexport * from \"./types\";\n"],"mappings":";AAAA;AAAA,EAKE,UAAAA;AAAA,OACK;;;ACJA,IAAM,iBAAiB;AAAA,EAC5B,OAAO;AACT;;;ACGA,SAAS,UAAAC,eAAc;;;ACPvB;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EAGE;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAGK;;;ACUA,IAAe,oBAAf,MAAiC;AAAC;AAKlC,IAAe,4BAAf,MAAyC;AAKhD;;;ADQA,IAAM,iCAAN,cAA6C,0BAA0B;AAAA,EAC7D;AAAA,EAER,YAAY,SAAkB;AAC5B,UAAM;AACN,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACf,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO,IAAI,sDAAsD;AACjE;AAAA,MACF,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO;AAAA,UACL;AAAA,QACF;AACA;AAAA,MACF,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO,IAAI,mDAAmD;AAC9D;AAAA,MACF;AACE,cAAM,IAAI;AAAA,UACR,qBAAqB,OAAO;AAAA,QAC9B;AAAA,IACJ;AAEA,SAAK,SAAS,WAAW,IAAI,YAAY,QAAQ,IAAI,IAAI,YAAY;AAAA,EACvE;AAAA,EAEA,MAAM,oBACJ,YACA,eACiC;AACjC,QAAI;AACF,aAAO,IAAI,gCAAgC,UAAU;AACrD,YAAM,WAA6B,MAAM,KAAK,OAAO;AAAA,QACnD;AAAA,QACA;AAAA,MACF;AACA,YAAM,QAAQ,SAAS,YAAY;AACnC,aAAO;AAAA,QACL,UAAU,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM,CAAC,CAAC;AAAA,SAAY,MAAM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AI,EAAE;AAC5C,YAAQ,QAAQ,KAAK,MAAM;AAAA,EAC7B;AACF;AAOO,IAAM,YAAY,CAAC,WAAqC;AAC7D,QAAM,aAAa,QAAQ,UAAU,eAAe;AACpD,QAAM,SAAS,UAAU,UAAU;AACnC,SAAO;AAAA,IACL,MAAM,OAAO,QAAQ;AAAA,IACrB,MAAM,OAAOC,SAAgC,YAA2B;AACtE,aAAO,MAAM;AAAA,QACX;AAAA,UACE,GAAGA;AAAA,UACH,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,aAAa,OAAO,eAAe;AAAA,IACnC,SAAS,OAAO,WAAW;AAAA,IAC3B,YAAY,CAAC;AAAA,IACb,WAAW,OAAO,aAAa;AAAA,IAC/B,UAAU,CAAC;AAAA,EACb;AACF;","names":["logger","logger","logger","logger","TEEMode","TappdClient","TEEMode","logger","TappdClient","logger","config"]} \ No newline at end of file diff --git a/package.json b/package.json index b44f305..0275800 100644 --- a/package.json +++ b/package.json @@ -7,14 +7,15 @@ "dependencies": { "@elizaos/core": "^1.0.0-beta.51", "@phala/dstack-sdk": "0.1.11", - "@solana/web3.js": "1.98.0", - "viem": "2.23.11" + "@solana/web3.js": "1.98.2", + "viem": "2.29.4" }, "devDependencies": { "@types/node": "^22.15.3", "prettier": "3.5.3", - "tsup": "8.4.0", - "typescript": "5.8.2" + "tsup": "8.5.0", + "typescript": "5.8.3", + "vitest": "^3.1.3" }, "scripts": { "build": "tsup", @@ -30,16 +31,16 @@ "gitHead": "646c632924826e2b75c2304a75ee56959fe4a460", "agentConfig": { "pluginType": "elizaos:plugin:1.0.0", - "pluginParameters": { - "TEE_VENDOR": { - "type": "string" - }, - "TEE_MODE": { - "type": "string" - }, - "WALLET_SECRET_SALT": { - "type": "string" - } + "pluginParameters": { + "TEE_VENDOR": { + "type": "string" + }, + "TEE_MODE": { + "type": "string" + }, + "WALLET_SECRET_SALT": { + "type": "string" + } } } } diff --git a/src/__tests__/deriveKey.test.ts b/src/__tests__/deriveKey.test.ts index b0ebcbc..7b18bbf 100644 --- a/src/__tests__/deriveKey.test.ts +++ b/src/__tests__/deriveKey.test.ts @@ -1,111 +1,123 @@ -import { TEEMode } from '@elizaos/core'; -import { TappdClient } from '@phala/dstack-sdk'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { DeriveKeyProvider } from '../providers/deriveKeyProvider'; +import { TEEMode } from "@elizaos/core"; +import { TappdClient } from "@phala/dstack-sdk"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { PhalaDeriveKeyProvider } from "../providers/deriveKeyProvider"; // Mock dependencies -vi.mock('@phala/dstack-sdk', () => ({ +vi.mock("@phala/dstack-sdk", () => ({ TappdClient: vi.fn().mockImplementation(() => ({ deriveKey: vi.fn().mockResolvedValue({ asUint8Array: () => new Uint8Array([1, 2, 3, 4, 5]), }), tdxQuote: vi.fn().mockResolvedValue({ - quote: 'mock-quote-data', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + quote: "mock-quote-data", + replayRtmrs: () => ["rtmr0", "rtmr1", "rtmr2", "rtmr3"], }), rawDeriveKey: vi.fn(), })), })); -vi.mock('@solana/web3.js', () => ({ +vi.mock("@solana/web3.js", () => ({ Keypair: { fromSeed: vi.fn().mockReturnValue({ publicKey: { - toBase58: () => 'mock-solana-public-key', + toBase58: () => "mock-solana-public-key", }, }), }, })); -vi.mock('viem/accounts', () => ({ +vi.mock("viem/accounts", () => ({ privateKeyToAccount: vi.fn().mockReturnValue({ - address: 'mock-evm-address', + address: "mock-evm-address", }), })); -describe('DeriveKeyProvider', () => { +describe("DeriveKeyProvider", () => { beforeEach(() => { vi.clearAllMocks(); }); - describe('constructor', () => { - it('should initialize with LOCAL mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + describe("constructor", () => { + it("should initialize with LOCAL mode", () => { + const _provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith("http://localhost:8090"); }); - it('should initialize with DOCKER mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + it("should initialize with DOCKER mode", () => { + const _provider = new PhalaDeriveKeyProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith( + "http://host.docker.internal:8090" + ); }); - it('should initialize with PRODUCTION mode', () => { - const _provider = new DeriveKeyProvider(TEEMode.PRODUCTION); + it("should initialize with PRODUCTION mode", () => { + const _provider = new PhalaDeriveKeyProvider(TEEMode.PRODUCTION); expect(TappdClient).toHaveBeenCalledWith(); }); - it('should throw error for invalid mode', () => { - expect(() => new DeriveKeyProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + it("should throw error for invalid mode", () => { + expect(() => new PhalaDeriveKeyProvider("INVALID_MODE")).toThrow( + "Invalid TEE_MODE" + ); }); }); - describe('rawDeriveKey', () => { - let _provider: DeriveKeyProvider; + describe("rawDeriveKey", () => { + let _provider: PhalaDeriveKeyProvider; beforeEach(() => { - _provider = new DeriveKeyProvider(TEEMode.LOCAL); + _provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); }); - it('should derive raw key successfully', async () => { - const path = 'test-path'; - const subject = 'test-subject'; + it("should derive raw key successfully", async () => { + const path = "test-path"; + const subject = "test-subject"; const result = await _provider.rawDeriveKey(path, subject); - const client = TappdClient.mock.results[0].value; + const client = vi.mocked(TappdClient).mock.results[0].value; expect(client.deriveKey).toHaveBeenCalledWith(path, subject); expect(result.asUint8Array()).toEqual(new Uint8Array([1, 2, 3, 4, 5])); }); - it('should handle errors during raw key derivation', async () => { - const mockError = new Error('Key derivation failed'); + it("should handle errors during raw key derivation", async () => { + const mockError = new Error("Key derivation failed"); vi.mocked(TappdClient).mockImplementationOnce(() => { const instance = new TappdClient(); instance.deriveKey = vi.fn().mockRejectedValueOnce(mockError); instance.tdxQuote = vi.fn(); - instance.rawDeriveKey = vi.fn(); + instance.deriveKey = vi.fn(); return instance; }); - const provider = new DeriveKeyProvider(TEEMode.LOCAL); - await expect(provider.rawDeriveKey('path', 'subject')).rejects.toThrow(mockError); + const provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); + await expect(provider.rawDeriveKey("path", "subject")).rejects.toThrow( + mockError + ); }); }); - describe('deriveEd25519Keypair', () => { - let provider: DeriveKeyProvider; + describe("deriveEd25519Keypair", () => { + let provider: PhalaDeriveKeyProvider; beforeEach(() => { - provider = new DeriveKeyProvider(TEEMode.LOCAL); + provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); }); - it('should derive Ed25519 keypair successfully', async () => { - const path = 'test-path'; - const subject = 'test-subject'; - const result = await provider.deriveEd25519Keypair(path, subject, 'test-agent-id'); + it("should derive Ed25519 keypair successfully", async () => { + const path = "test-path"; + const subject = "test-subject"; + const result = await provider.deriveEd25519Keypair( + path, + subject, + "test-agent-id" + ); - const client = TappdClient.mock.results[0].value; + const client = vi.mocked(TappdClient).mock.results[0].value; expect(client.deriveKey).toHaveBeenCalledWith(path, subject); - expect(result.keypair.publicKey.toBase58()).toEqual('mock-solana-public-key'); + expect(result.keypair.publicKey.toBase58()).toEqual( + "mock-solana-public-key" + ); }); }); }); diff --git a/src/__tests__/remoteAttestation.test.ts b/src/__tests__/remoteAttestation.test.ts index 740bfff..509e051 100644 --- a/src/__tests__/remoteAttestation.test.ts +++ b/src/__tests__/remoteAttestation.test.ts @@ -1,82 +1,91 @@ -import { TEEMode } from '@elizaos/core'; -import { TappdClient } from '@phala/dstack-sdk'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; +import { TEEMode } from "@elizaos/core"; +import { TappdClient } from "@phala/dstack-sdk"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { PhalaRemoteAttestationProvider } from "../providers/remoteAttestationProvider"; // Mock TappdClient -vi.mock('@phala/dstack-sdk', () => ({ +vi.mock("@phala/dstack-sdk", () => ({ TappdClient: vi.fn().mockImplementation(() => ({ tdxQuote: vi.fn().mockResolvedValue({ - quote: 'mock-quote-data', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + quote: "mock-quote-data", + replayRtmrs: () => ["rtmr0", "rtmr1", "rtmr2", "rtmr3"], }), deriveKey: vi.fn(), + endpoint: "http://localhost:8090", + info: vi.fn().mockResolvedValue({}), })), })); -describe('RemoteAttestationProvider', () => { +describe("PhalaRemoteAttestationProvider", () => { beforeEach(() => { vi.clearAllMocks(); }); - describe('constructor', () => { - it('should initialize with LOCAL mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith('http://localhost:8090'); + describe("constructor", () => { + it("should initialize with LOCAL mode", () => { + const _provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); + expect(TappdClient).toHaveBeenCalledWith("http://localhost:8090"); }); - it('should initialize with DOCKER mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith('http://host.docker.internal:8090'); + it("should initialize with DOCKER mode", () => { + const _provider = new PhalaRemoteAttestationProvider(TEEMode.DOCKER); + expect(TappdClient).toHaveBeenCalledWith( + "http://host.docker.internal:8090" + ); }); - it('should initialize with PRODUCTION mode', () => { - const _provider = new RemoteAttestationProvider(TEEMode.PRODUCTION); + it("should initialize with PRODUCTION mode", () => { + const _provider = new PhalaRemoteAttestationProvider(TEEMode.PRODUCTION); expect(TappdClient).toHaveBeenCalledWith(); }); - it('should throw error for invalid mode', () => { - expect(() => new RemoteAttestationProvider('INVALID_MODE')).toThrow('Invalid TEE_MODE'); + it("should throw error for invalid mode", () => { + expect(() => new PhalaRemoteAttestationProvider("INVALID_MODE")).toThrow( + "Invalid TEE_MODE" + ); }); }); - describe('generateAttestation', () => { - let provider: RemoteAttestationProvider; + describe("generateAttestation", () => { + let provider: PhalaRemoteAttestationProvider; beforeEach(() => { - provider = new RemoteAttestationProvider(TEEMode.LOCAL); + provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); }); - it('should generate attestation successfully', async () => { - const reportData = 'test-report-data'; + it("should generate attestation successfully", async () => { + const reportData = "test-report-data"; const quote = await provider.generateAttestation(reportData); expect(quote).toEqual({ - quote: 'mock-quote-data', + quote: "mock-quote-data", timestamp: expect.any(Number), }); }); - it('should handle errors during attestation generation', async () => { - const mockError = new Error('TDX Quote generation failed'); + it("should handle errors during attestation generation", async () => { + const mockError = new Error("TDX Quote generation failed"); const mockTdxQuote = vi.fn().mockRejectedValue(mockError); - vi.mocked(TappdClient).mockImplementationOnce(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - })); + vi.mocked(TappdClient).mockImplementationOnce( + () => + ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + }) as unknown as TappdClient + ); - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(provider.generateAttestation('test-data')).rejects.toThrow( - 'Failed to generate TDX Quote' + const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); + await expect(provider.generateAttestation("test-data")).rejects.toThrow( + "Failed to generate TDX Quote" ); }); - it('should pass hash algorithm to tdxQuote when provided', async () => { - const reportData = 'test-report-data'; - const hashAlgorithm = 'raw'; + it("should pass hash algorithm to tdxQuote when provided", async () => { + const reportData = "test-report-data"; + const hashAlgorithm = "raw"; await provider.generateAttestation(reportData, hashAlgorithm); - const client = TappdClient.mock.results[0].value; + const client = vi.mocked(TappdClient).mock.results[0].value; expect(client.tdxQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); }); }); diff --git a/src/__tests__/timeout.test.ts b/src/__tests__/timeout.test.ts index 9fe7b24..136232a 100644 --- a/src/__tests__/timeout.test.ts +++ b/src/__tests__/timeout.test.ts @@ -1,111 +1,140 @@ -import { TEEMode } from '@elizaos/core'; -import { TappdClient } from '@phala/dstack-sdk'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { DeriveKeyProvider } from '../providers/deriveKeyProvider'; -import { RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; +import { TEEMode } from "@elizaos/core"; +import { TappdClient } from "@phala/dstack-sdk"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { PhalaDeriveKeyProvider } from "../providers/deriveKeyProvider"; +import { PhalaRemoteAttestationProvider } from "../providers/remoteAttestationProvider"; // Mock TappdClient -vi.mock('@phala/dstack-sdk', () => ({ +vi.mock("@phala/dstack-sdk", () => ({ TappdClient: vi.fn().mockImplementation(() => ({ tdxQuote: vi.fn(), deriveKey: vi.fn(), + endpoint: "http://localhost:8090", // Add this + info: vi.fn().mockResolvedValue({}), // Add this })), })); -describe('TEE Provider Timeout Tests', () => { +describe("TEE Provider Timeout Tests", () => { beforeEach(() => { vi.clearAllMocks(); }); - describe('RemoteAttestationProvider', () => { - it('should handle API timeout during attestation generation', async () => { - const mockTdxQuote = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(() => provider.generateAttestation('test-data')).rejects.toThrow( - 'Failed to generate TDX Quote: Request timed out' + describe("PhalaRemoteAttestationProvider", () => { + it("should handle API timeout during attestation generation", async () => { + const mockTdxQuote = vi + .fn() + .mockRejectedValueOnce(new Error("Request timed out")); + + vi.mocked(TappdClient).mockImplementation( + () => + ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + }) as unknown as TappdClient ); + const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => + provider.generateAttestation("test-data") + ).rejects.toThrow("Failed to generate TDX Quote: Request timed out"); + // Verify the call was made once expect(mockTdxQuote).toHaveBeenCalledTimes(1); - expect(mockTdxQuote).toHaveBeenCalledWith('test-data', undefined); + expect(mockTdxQuote).toHaveBeenCalledWith("test-data", undefined); }); - it('should handle network errors during attestation generation', async () => { - const mockTdxQuote = vi.fn().mockRejectedValueOnce(new Error('Network error')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - })); - - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - await expect(() => provider.generateAttestation('test-data')).rejects.toThrow( - 'Failed to generate TDX Quote: Network error' + it("should handle network errors during attestation generation", async () => { + const mockTdxQuote = vi + .fn() + .mockRejectedValueOnce(new Error("Network error")); + + vi.mocked(TappdClient).mockImplementation( + () => + ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + }) as unknown as TappdClient ); + const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); + await expect(() => + provider.generateAttestation("test-data") + ).rejects.toThrow("Failed to generate TDX Quote: Network error"); + expect(mockTdxQuote).toHaveBeenCalledTimes(1); }); - it('should handle successful attestation generation', async () => { + it("should handle successful attestation generation", async () => { const mockQuote = { - quote: 'test-quote', - replayRtmrs: () => ['rtmr0', 'rtmr1', 'rtmr2', 'rtmr3'], + quote: "test-quote", + replayRtmrs: () => ["rtmr0", "rtmr1", "rtmr2", "rtmr3"], }; const mockTdxQuote = vi.fn().mockResolvedValueOnce(mockQuote); - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - })); + vi.mocked(TappdClient).mockImplementation( + () => + ({ + tdxQuote: mockTdxQuote, + deriveKey: vi.fn(), + }) as unknown as TappdClient + ); - const provider = new RemoteAttestationProvider(TEEMode.LOCAL); - const result = await provider.generateAttestation('test-data'); + const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); + const result = await provider.generateAttestation("test-data"); expect(mockTdxQuote).toHaveBeenCalledTimes(1); expect(result).toEqual({ - quote: 'test-quote', + quote: "test-quote", timestamp: expect.any(Number), }); }); }); - describe('DeriveKeyProvider', () => { - it('should handle API timeout during key derivation', async () => { - const mockDeriveKey = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: mockDeriveKey, - })); - - const provider = new DeriveKeyProvider(TEEMode.LOCAL); - await expect(() => provider.rawDeriveKey('test-path', 'test-subject')).rejects.toThrow( - 'Request timed out' + describe("PhalaDeriveKeyProvider", () => { + it("should handle API timeout during key derivation", async () => { + const mockDeriveKey = vi + .fn() + .mockRejectedValueOnce(new Error("Request timed out")); + + vi.mocked(TappdClient).mockImplementation( + () => + ({ + tdxQuote: vi.fn(), + deriveKey: vi.fn(), + }) as unknown as TappdClient ); + const provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); + await expect(() => + provider.rawDeriveKey("test-path", "test-subject") + ).rejects.toThrow("Request timed out"); + expect(mockDeriveKey).toHaveBeenCalledTimes(1); - expect(mockDeriveKey).toHaveBeenCalledWith('test-path', 'test-subject'); + expect(mockDeriveKey).toHaveBeenCalledWith("test-path", "test-subject"); }); - it('should handle API timeout during Ed25519 key derivation', async () => { - const mockDeriveKey = vi.fn().mockRejectedValueOnce(new Error('Request timed out')); - - vi.mocked(TappdClient).mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: mockDeriveKey, - })); + it("should handle API timeout during Ed25519 key derivation", async () => { + const mockDeriveKey = vi + .fn() + .mockRejectedValueOnce(new Error("Request timed out")); + + vi.mocked(TappdClient).mockImplementation( + () => + ({ + tdxQuote: vi.fn(), + deriveKey: vi.fn(), + }) as unknown as TappdClient + ); - const provider = new DeriveKeyProvider(TEEMode.LOCAL); + const provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); await expect(() => - provider.deriveEd25519Keypair('test-path', 'test-subject') - ).rejects.toThrow('Request timed out'); + provider.deriveEd25519Keypair( + "test-path", + "test-subject", + "test-agent-id" + ) + ).rejects.toThrow("Request timed out"); expect(mockDeriveKey).toHaveBeenCalledTimes(1); }); diff --git a/src/actions/remoteAttestationAction.ts b/src/actions/remoteAttestationAction.ts index 7ad0579..6409a95 100644 --- a/src/actions/remoteAttestationAction.ts +++ b/src/actions/remoteAttestationAction.ts @@ -4,10 +4,10 @@ import type { Memory, RemoteAttestationMessage, State, -} from '@elizaos/core'; -import { logger } from '@elizaos/core'; -import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from '../providers/remoteAttestationProvider'; -import { hexToUint8Array } from '../utils'; +} from "@elizaos/core"; +import { logger } from "@elizaos/core"; +import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from "../providers/remoteAttestationProvider"; +import { hexToUint8Array } from "../utils"; /** * Asynchronously uploads a Uint8Array as a binary file to a specified URL. @@ -16,12 +16,12 @@ import { hexToUint8Array } from '../utils'; * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object. */ async function uploadUint8Array(data: Uint8Array) { - const blob = new Blob([data], { type: 'application/octet-stream' }); + const blob = new Blob([data], { type: "application/octet-stream" }); const formData = new FormData(); - formData.append('file', blob, 'quote.bin'); + formData.append("file", blob, "quote.bin"); - return await fetch('https://proof.t16z.com/api/upload', { - method: 'POST', + return await fetch("https://proof.t16z.com/api/upload", { + method: "POST", body: formData as BodyInit, }); } @@ -34,22 +34,23 @@ async function uploadUint8Array(data: Uint8Array) { * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}} */ export const phalaRemoteAttestationAction = { - name: 'REMOTE_ATTESTATION', + name: "REMOTE_ATTESTATION", similes: [ - 'REMOTE_ATTESTATION', - 'TEE_REMOTE_ATTESTATION', - 'TEE_ATTESTATION', - 'TEE_QUOTE', - 'ATTESTATION', - 'TEE_ATTESTATION_QUOTE', + "REMOTE_ATTESTATION", + "TEE_REMOTE_ATTESTATION", + "TEE_ATTESTATION", + "TEE_QUOTE", + "ATTESTATION", + "TEE_ATTESTATION_QUOTE", ], - description: 'Generate a remote attestation to prove that the agent is running in a TEE', + description: + "Generate a remote attestation to prove that the agent is running in a TEE", handler: async ( runtime: IAgentRuntime, message: Memory, - _state: State, - _options: { [key: string]: unknown }, - callback: HandlerCallback + _state?: State, + _options?: { [key: string]: unknown }, + callback?: HandlerCallback ) => { try { // Attestation will be generated based on the message info @@ -59,28 +60,32 @@ export const phalaRemoteAttestationAction = { message: { entityId: message.entityId, roomId: message.roomId, - content: message.content.text, + content: message.content.text || "", }, }; // Get the remote attestation of the agentId - const teeMode = runtime.getSetting('TEE_MODE'); + const teeMode = runtime.getSetting("TEE_MODE"); logger.debug(`Tee mode: ${teeMode}`); - logger.debug(`Attestation message: ${JSON.stringify(attestationMessage)}`); + logger.debug( + `Attestation message: ${JSON.stringify(attestationMessage)}` + ); const provider = new RemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + const attestation = await provider.generateAttestation( + JSON.stringify(attestationMessage) + ); const attestationData = hexToUint8Array(attestation.quote); const response = await uploadUint8Array(attestationData); const data = await response.json(); - callback({ + callback?.({ text: `Here's my 🧾 RA Quote 🫡 https://proof.t16z.com/reports/${data.checksum}`, - actions: ['NONE'], + actions: ["NONE"], }); return true; } catch (error) { - console.error('Failed to fetch remote attestation: ', error); + console.error("Failed to fetch remote attestation: ", error); return false; } }, @@ -90,46 +95,46 @@ https://proof.t16z.com/reports/${data.checksum}`, examples: [ [ { - name: '{{name1}}', + name: "{{name1}}", content: { - text: 'If you are running in a TEE, generate a remote attestation', + text: "If you are running in a TEE, generate a remote attestation", }, }, { - name: '{{agentName}}', + name: "{{agentName}}", content: { - text: 'Of course, one second...', - actions: ['REMOTE_ATTESTATION'], + text: "Of course, one second...", + actions: ["REMOTE_ATTESTATION"], }, }, ], [ { - name: '{{name1}}', + name: "{{name1}}", content: { - text: 'Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?', + text: "Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?", }, }, { - name: '{{agentName}}', + name: "{{agentName}}", content: { - text: 'I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!', - actions: ['REMOTE_ATTESTATION'], + text: "I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!", + actions: ["REMOTE_ATTESTATION"], }, }, ], [ { - name: '{{name1}}', + name: "{{name1}}", content: { text: "It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'", }, }, { - name: '{{agentName}}', + name: "{{agentName}}", content: { - text: 'Oh, dear...lemme find that for you', - actions: ['REMOTE_ATTESTATION'], + text: "Oh, dear...lemme find that for you", + actions: ["REMOTE_ATTESTATION"], }, }, ], diff --git a/src/index.ts b/src/index.ts index c152d35..c187ba0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,13 +4,13 @@ import { type TeePluginConfig, type TeeVendorConfig, logger, -} from '@elizaos/core'; -import { TeeVendorNames } from './vendors/types'; -import { getVendor } from './vendors/index'; +} from "@elizaos/core"; +import { TeeVendorNames } from "./vendors/types"; +import { getVendor } from "./vendors/index"; -export { phalaRemoteAttestationAction } from './actions/remoteAttestationAction'; -export { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider'; -export { PhalaRemoteAttestationProvider } from './providers/remoteAttestationProvider'; +export { phalaRemoteAttestationAction } from "./actions/remoteAttestationAction"; +export { PhalaDeriveKeyProvider } from "./providers/deriveKeyProvider"; +export { PhalaRemoteAttestationProvider } from "./providers/remoteAttestationProvider"; export type { TeeVendorConfig }; /** @@ -19,13 +19,16 @@ export type { TeeVendorConfig }; * @param {IAgentRuntime} runtime - The runtime object with TEE related settings. * @returns {Promise} - A promise that resolves once the TEE is initialized. */ -async function initializeTEE(config: Record, runtime: IAgentRuntime) { - if (config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR')) { - const vendor = config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR'); +async function initializeTEE( + config: Record, + runtime: IAgentRuntime +) { + if (config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR")) { + const vendor = config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR"); logger.info(`Initializing TEE with vendor: ${vendor}`); let plugin: Plugin; switch (vendor) { - case 'phala': + case "phala": plugin = teePlugin({ vendor: TeeVendorNames.PHALA, }); diff --git a/src/providers/base.ts b/src/providers/base.ts index cf85fd6..62d497d 100644 --- a/src/providers/base.ts +++ b/src/providers/base.ts @@ -1,5 +1,5 @@ -import type { RemoteAttestationQuote } from '@elizaos/core'; -import type { TdxQuoteHashAlgorithms } from '@phala/dstack-sdk'; +import type { RemoteAttestationQuote } from "@elizaos/core"; +import type { TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; /** * Abstract class for deriving keys from the TEE. diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index 56353e8..bdaa5c2 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -1,11 +1,21 @@ -import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core'; -import { type DeriveKeyAttestationData, type RemoteAttestationQuote, TEEMode } from '@elizaos/core'; -import { type DeriveKeyResponse, TappdClient } from '@phala/dstack-sdk'; -import { Keypair } from '@solana/web3.js'; -import { toViemAccount } from '@phala/dstack-sdk/viem'; -import { toKeypair } from '@phala/dstack-sdk/solana'; -import { DeriveKeyProvider } from './base'; -import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from './remoteAttestationProvider'; +import { + type IAgentRuntime, + type Memory, + type Provider, + logger, +} from "@elizaos/core"; +import { + type DeriveKeyAttestationData, + type RemoteAttestationQuote, + TEEMode, +} from "@elizaos/core"; +import { type DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; +import { Keypair } from "@solana/web3.js"; +import { toViemAccount } from "@phala/dstack-sdk/viem"; +import { toKeypair } from "@phala/dstack-sdk/solana"; +import { DeriveKeyProvider } from "./base"; +import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from "./remoteAttestationProvider"; +import { PrivateKeyAccount } from "viem"; /** * Phala TEE Cloud Provider @@ -29,19 +39,23 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { // Both LOCAL and DOCKER modes use the simulator, just with different endpoints switch (teeMode) { case TEEMode.LOCAL: - endpoint = 'http://localhost:8090'; - logger.log('TEE: Connecting to local simulator at localhost:8090'); + endpoint = "http://localhost:8090"; + logger.log("TEE: Connecting to local simulator at localhost:8090"); break; case TEEMode.DOCKER: - endpoint = 'http://host.docker.internal:8090'; - logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090'); + endpoint = "http://host.docker.internal:8090"; + logger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); break; case TEEMode.PRODUCTION: endpoint = undefined; - logger.log('TEE: Running in production mode without simulator'); + logger.log("TEE: Running in production mode without simulator"); break; default: - throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); } this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); @@ -59,9 +73,9 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { subject, }; const reportdata = JSON.stringify(deriveKeyData); - logger.log('Generating Remote Attestation Quote for Derive Key...'); + logger.log("Generating Remote Attestation Quote for Derive Key..."); const quote = await this.raProvider.generateAttestation(reportdata); - logger.log('Remote Attestation Quote generated successfully!'); + logger.log("Remote Attestation Quote generated successfully!"); return quote; } @@ -71,19 +85,22 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { * @param subject - The subject to derive the key from. This is used for the certificate chain. * @returns The derived key. */ - async rawDeriveKey(path: string, subject: string): Promise { + async rawDeriveKey( + path: string, + subject: string + ): Promise { try { if (!path || !subject) { - logger.error('Path and Subject are required for key derivation'); + logger.error("Path and Subject are required for key derivation"); } - logger.log('Deriving Raw Key in TEE...'); + logger.log("Deriving Raw Key in TEE..."); const derivedKey = await this.client.deriveKey(path, subject); - logger.log('Raw Key Derived Successfully!'); + logger.log("Raw Key Derived Successfully!"); return derivedKey; } catch (error) { - logger.error('Error deriving raw key:', error); + logger.error("Error deriving raw key:", error); throw error; } } @@ -102,23 +119,23 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { try { if (!path || !subject) { - logger.error('Path and Subject are required for key derivation'); + logger.error("Path and Subject are required for key derivation"); } - logger.log('Deriving Key in TEE...'); + logger.log("Deriving Key in TEE..."); const derivedKey = await this.client.deriveKey(path, subject); - const keypair = toKeypair(derivedKey); + const keypair = toKeypair(derivedKey) as unknown as Keypair; // Generate an attestation for the derived key data for public to verify const attestation = await this.generateDeriveKeyAttestation( agentId, keypair.publicKey.toBase58() ); - logger.log('Key Derived Successfully!'); + logger.log("Key Derived Successfully!"); return { keypair, attestation }; } catch (error) { - logger.error('Error deriving key:', error); + logger.error("Error deriving key:", error); throw error; } } @@ -140,20 +157,28 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { }> { try { if (!path || !subject) { - logger.error('Path and Subject are required for key derivation'); + logger.error("Path and Subject are required for key derivation"); } - logger.log('Deriving ECDSA Key in TEE...'); - const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(path, subject); - const keypair = toViemAccount(deriveKeyResponse); + logger.log("Deriving ECDSA Key in TEE..."); + const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey( + path, + subject + ); + const keypair = toViemAccount( + deriveKeyResponse + ) as unknown as PrivateKeyAccount; // Generate an attestation for the derived key data for public to verify - const attestation = await this.generateDeriveKeyAttestation(agentId, keypair.address); - logger.log('ECDSA Key Derived Successfully!'); + const attestation = await this.generateDeriveKeyAttestation( + agentId, + keypair.address + ); + logger.log("ECDSA Key Derived Successfully!"); return { keypair, attestation }; } catch (error) { - logger.error('Error deriving ecdsa key:', error); + logger.error("Error deriving ecdsa key:", error); throw error; } } @@ -167,26 +192,38 @@ interface ProviderResult { } const phalaDeriveKeyProvider: Provider = { - name: 'phala-derive-key', - get: async (runtime: IAgentRuntime, _message?: Memory): Promise => { - const teeMode = runtime.getSetting('TEE_MODE'); + name: "phala-derive-key", + get: async ( + runtime: IAgentRuntime, + _message?: Memory + ): Promise => { + const teeMode = runtime.getSetting("TEE_MODE"); const provider = new PhalaDeriveKeyProvider(teeMode); const agentId = runtime.agentId; try { // Validate wallet configuration - if (!runtime.getSetting('WALLET_SECRET_SALT')) { - logger.error('Wallet secret salt is not configured in settings'); + if (!runtime.getSetting("WALLET_SECRET_SALT")) { + logger.error("Wallet secret salt is not configured in settings"); return { data: null, values: {}, - text: 'Wallet secret salt is not configured in settings', + text: "Wallet secret salt is not configured in settings", }; } try { - const secretSalt = runtime.getSetting('WALLET_SECRET_SALT') || 'secret_salt'; - const solanaKeypair = await provider.deriveEd25519Keypair(secretSalt, 'solana', agentId); - const evmKeypair = await provider.deriveEcdsaKeypair(secretSalt, 'evm', agentId); + const secretSalt = + runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; + const solanaKeypair = await provider.deriveEd25519Keypair( + secretSalt, + "solana", + agentId + ); + const evmKeypair = await provider.deriveEcdsaKeypair( + secretSalt, + "evm", + agentId + ); // Original data structure const walletData = { @@ -209,23 +246,23 @@ const phalaDeriveKeyProvider: Provider = { text: text, }; } catch (error) { - logger.error('Error creating PublicKey:', error); + logger.error("Error creating PublicKey:", error); return { data: null, values: {}, text: `Error creating PublicKey: ${ - error instanceof Error ? error.message : 'Unknown error' + error instanceof Error ? error.message : "Unknown error" }`, }; } - } catch (error) { - logger.error('Error in derive key provider:', error.message); + } catch (error: unknown) { + const errorMessage = + error instanceof Error ? error.message : "Unknown error"; + logger.error("Error in derive key provider:", errorMessage); return { data: null, values: {}, - text: `Failed to fetch derive key information: ${ - error instanceof Error ? error.message : 'Unknown error' - }`, + text: `Failed to fetch derive key information: ${errorMessage}`, }; } }, diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts index 46c8246..316b8d0 100644 --- a/src/providers/remoteAttestationProvider.ts +++ b/src/providers/remoteAttestationProvider.ts @@ -1,7 +1,20 @@ -import { type IAgentRuntime, type Memory, type Provider, logger } from '@elizaos/core'; -import { type RemoteAttestationMessage, type RemoteAttestationQuote, TEEMode } from '@elizaos/core'; -import { TappdClient, type TdxQuoteHashAlgorithms, type TdxQuoteResponse } from '@phala/dstack-sdk'; -import { RemoteAttestationProvider } from './base'; +import { + type IAgentRuntime, + type Memory, + type Provider, + logger, +} from "@elizaos/core"; +import { + type RemoteAttestationMessage, + type RemoteAttestationQuote, + TEEMode, +} from "@elizaos/core"; +import { + TappdClient, + type TdxQuoteHashAlgorithms, + type TdxQuoteResponse, +} from "@phala/dstack-sdk"; +import { RemoteAttestationProvider } from "./base"; // Define the ProviderResult interface if not already imported /** @@ -38,19 +51,23 @@ class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { // Both LOCAL and DOCKER modes use the simulator, just with different endpoints switch (teeMode) { case TEEMode.LOCAL: - endpoint = 'http://localhost:8090'; - logger.log('TEE: Connecting to local simulator at localhost:8090'); + endpoint = "http://localhost:8090"; + logger.log("TEE: Connecting to local simulator at localhost:8090"); break; case TEEMode.DOCKER: - endpoint = 'http://host.docker.internal:8090'; - logger.log('TEE: Connecting to simulator via Docker at host.docker.internal:8090'); + endpoint = "http://host.docker.internal:8090"; + logger.log( + "TEE: Connecting to simulator via Docker at host.docker.internal:8090" + ); break; case TEEMode.PRODUCTION: endpoint = undefined; - logger.log('TEE: Running in production mode without simulator'); + logger.log("TEE: Running in production mode without simulator"); break; default: - throw new Error(`Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`); + throw new Error( + `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` + ); } this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); @@ -61,20 +78,25 @@ class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { hashAlgorithm?: TdxQuoteHashAlgorithms ): Promise { try { - logger.log('Generating attestation for: ', reportData); - const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(reportData, hashAlgorithm); + logger.log("Generating attestation for: ", reportData); + const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote( + reportData, + hashAlgorithm + ); const rtmrs = tdxQuote.replayRtmrs(); - logger.log(`rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f`); + logger.log( + `rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f` + ); const quote: RemoteAttestationQuote = { quote: tdxQuote.quote, timestamp: Date.now(), }; - logger.log('Remote attestation quote: ', quote); + logger.log("Remote attestation quote: ", quote); return quote; } catch (error) { - console.error('Error generating remote attestation:', error); + console.error("Error generating remote attestation:", error); throw new Error( - `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}` + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` ); } } @@ -82,9 +104,9 @@ class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { // Keep the original provider for backwards compatibility const phalaRemoteAttestationProvider: Provider = { - name: 'phala-remote-attestation', + name: "phala-remote-attestation", get: async (runtime: IAgentRuntime, message: Memory) => { - const teeMode = runtime.getSetting('TEE_MODE'); + const teeMode = runtime.getSetting("TEE_MODE"); const provider = new PhalaRemoteAttestationProvider(teeMode); const agentId = runtime.agentId; @@ -95,11 +117,16 @@ const phalaRemoteAttestationProvider: Provider = { message: { entityId: message.entityId, roomId: message.roomId, - content: message.content.text, + content: message.content.text || "", }, }; - logger.log('Generating attestation for: ', JSON.stringify(attestationMessage)); - const attestation = await provider.generateAttestation(JSON.stringify(attestationMessage)); + logger.log( + "Generating attestation for: ", + JSON.stringify(attestationMessage) + ); + const attestation = await provider.generateAttestation( + JSON.stringify(attestationMessage) + ); return { text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`, data: { @@ -111,9 +138,9 @@ const phalaRemoteAttestationProvider: Provider = { }, }; } catch (error) { - console.error('Error in remote attestation provider:', error); + console.error("Error in remote attestation provider:", error); throw new Error( - `Failed to generate TDX Quote: ${error instanceof Error ? error.message : 'Unknown error'}` + `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` ); } }, diff --git a/src/types.ts b/src/types.ts index 6a85619..7806e3f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -5,6 +5,6 @@ */ export enum TeeType { - SGX_GRAMINE = 'sgx_gramine', - TDX_DSTACK = 'tdx_dstack', -} \ No newline at end of file + SGX_GRAMINE = "sgx_gramine", + TDX_DSTACK = "tdx_dstack", +} diff --git a/src/utils.ts b/src/utils.ts index c2f6fbe..57f2a1c 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,4 @@ -import { createHash } from 'node:crypto'; +import { createHash } from "node:crypto"; /** * Converts a hexadecimal string to a Uint8Array. @@ -8,19 +8,19 @@ import { createHash } from 'node:crypto'; * @throws {Error} - If the input hex string is invalid. */ export function hexToUint8Array(hex: string) { - const hexString = hex.trim().replace(/^0x/, ''); + const hexString = hex.trim().replace(/^0x/, ""); if (!hexString) { - throw new Error('Invalid hex string'); + throw new Error("Invalid hex string"); } if (hexString.length % 2 !== 0) { - throw new Error('Invalid hex string'); + throw new Error("Invalid hex string"); } const array = new Uint8Array(hexString.length / 2); for (let i = 0; i < hexString.length; i += 2) { const byte = Number.parseInt(hexString.slice(i, i + 2), 16); if (Number.isNaN(byte)) { - throw new Error('Invalid hex string'); + throw new Error("Invalid hex string"); } array[i / 2] = byte; } @@ -35,7 +35,7 @@ export function hexToUint8Array(hex: string) { * @returns {Buffer} - The calculated SHA256 hash as a Buffer object. */ export function calculateSHA256(input: string): Buffer { - const hash = createHash('sha256'); + const hash = createHash("sha256"); hash.update(input); return hash.digest(); } diff --git a/src/vendors/index.ts b/src/vendors/index.ts index 6cd82ba..da6b322 100644 --- a/src/vendors/index.ts +++ b/src/vendors/index.ts @@ -1,9 +1,9 @@ -import { PhalaVendor } from './phala'; -import type { TeeVendor } from './types'; -import { type TeeVendorName, TeeVendorNames } from './types'; +import { PhalaVendor } from "./phala"; +import type { TeeVendor } from "./types"; +import { type TeeVendorName, TeeVendorNames } from "./types"; const vendors: Record = { - [TeeVendorNames.PHALA]: new PhalaVendor(), + [TeeVendorNames.PHALA]: new PhalaVendor() as TeeVendor, }; export const getVendor = (type: TeeVendorName): TeeVendor => { @@ -14,4 +14,4 @@ export const getVendor = (type: TeeVendorName): TeeVendor => { return vendor; }; -export * from './types'; +export * from "./types"; diff --git a/src/vendors/phala.ts b/src/vendors/phala.ts index 970a728..21fb363 100644 --- a/src/vendors/phala.ts +++ b/src/vendors/phala.ts @@ -1,7 +1,7 @@ -import { phalaRemoteAttestationAction as remoteAttestationAction } from '../actions/remoteAttestationAction'; -import { phalaDeriveKeyProvider as deriveKeyProvider } from '../providers/deriveKeyProvider'; -import { phalaRemoteAttestationProvider as remoteAttestationProvider } from '../providers/remoteAttestationProvider'; -import { type TeeVendor, TeeVendorNames } from './types'; +import { phalaRemoteAttestationAction as remoteAttestationAction } from "../actions/remoteAttestationAction"; +import { phalaDeriveKeyProvider as deriveKeyProvider } from "../providers/deriveKeyProvider"; +import { phalaRemoteAttestationProvider as remoteAttestationProvider } from "../providers/remoteAttestationProvider"; +import { type TeeVendor, TeeVendorNames } from "./types"; /** * A class representing a vendor for Phala TEE. @@ -45,7 +45,7 @@ export class PhalaVendor implements TeeVendor { * @returns {string} The name of the plugin. */ getName() { - return 'phala-tee-plugin'; + return "phala-tee-plugin"; } /** @@ -53,6 +53,6 @@ export class PhalaVendor implements TeeVendor { * @returns {string} The description of the function */ getDescription() { - return 'Phala TEE Cloud to Host Eliza Agents'; + return "Phala TEE Cloud to Host Eliza Agents"; } } diff --git a/src/vendors/types.ts b/src/vendors/types.ts index 2cb9c8b..32e59a3 100644 --- a/src/vendors/types.ts +++ b/src/vendors/types.ts @@ -1,14 +1,16 @@ -import type { Action, Provider } from '@elizaos/core'; +import type { Action, Provider } from "@elizaos/core"; export const TeeVendorNames = { - PHALA: 'phala', + PHALA: "phala", } as const; /** * Type representing the name of a Tee vendor. * It can either be one of the keys of TeeVendorNames or a string. */ -export type TeeVendorName = (typeof TeeVendorNames)[keyof typeof TeeVendorNames] | string; +export type TeeVendorName = + | (typeof TeeVendorNames)[keyof typeof TeeVendorNames] + | string; /** * Interface for a TeeVendor, representing a vendor that sells tees. diff --git a/tsconfig.json b/tsconfig.json index e168e2b..3c3c58b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,10 +2,19 @@ "compilerOptions": { "outDir": "dist", "rootDir": "src", - "module": "ESNext", + "baseUrl": "../..", + "lib": ["ESNext", "DOM"], "target": "ESNext", - "types": ["node"], - "baseUrl": ".", + "module": "Preserve", + "moduleResolution": "Bundler", + "strict": true, + "esModuleInterop": true, + "allowImportingTsExtensions": true, + "declaration": true, + "emitDeclarationOnly": true, + "resolveJsonModule": true, + "moduleDetection": "force", + "allowArbitraryExtensions": true, "paths": { "@elizaos/core": ["../core/src"], "@elizaos/core/*": ["../core/src/*"] diff --git a/tsup.config.ts b/tsup.config.ts index b91996a..2719330 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -6,7 +6,7 @@ export default defineConfig({ tsconfig: './tsconfig.build.json', // Use build-specific tsconfig sourcemap: true, format: ['esm'], // Ensure you're targeting CommonJS - dts: false, // Skip DTS generation to avoid external import issues // Ensure you're targeting CommonJS + dts: true, external: [ 'dotenv', // Externalize dotenv to prevent bundling 'fs', // Externalize fs to use Node.js built-in module From 2423caf3a5ab11edddb90306c7b12ca664ec0f8e Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Sat, 17 May 2025 17:25:54 -0600 Subject: [PATCH 18/39] bump version --- bun.lock | 26 +++++--------------------- package.json | 4 ++-- 2 files changed, 7 insertions(+), 23 deletions(-) diff --git a/bun.lock b/bun.lock index 6606b69..8babca8 100644 --- a/bun.lock +++ b/bun.lock @@ -4,17 +4,17 @@ "": { "name": "@elizaos/plugin-tee", "dependencies": { - "@elizaos/core": "^1.0.0-beta.51", + "@elizaos/core": "^1.0.0-beta.52", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.2", "viem": "2.29.4", - "vitest": "^3.1.3", }, "devDependencies": { "@types/node": "^22.15.3", "prettier": "3.5.3", "tsup": "8.5.0", "typescript": "5.8.3", + "vitest": "^3.1.3", }, }, }, @@ -305,10 +305,6 @@ "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - "bigint-buffer": ["bigint-buffer@1.1.5", "", { "dependencies": { "bindings": "^1.3.0" } }, "sha512-trfYco6AoZ+rKhKnxA0hgX0HAbVP/s808/EuDSe2JDzUnCp/xAsli35Orvk67UrTEcwuxZqYZDmfA2RXJgxVvA=="], - - "bindings": ["bindings@1.5.0", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="], - "bn.js": ["bn.js@5.2.2", "", {}, "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw=="], "borsh": ["borsh@0.7.0", "", { "dependencies": { "bn.js": "^5.2.0", "bs58": "^4.0.0", "text-encoding-utf-8": "^1.0.2" } }, "sha512-CLCsZGIBCFnPtkNnieW/a8wmreDmfUtjU2m9yHrzPXIlNbqVs0AQrSatSG6vdNYUqdc83tkQi2eHfF98ubzQLA=="], @@ -455,8 +451,6 @@ "fdir": ["fdir@6.4.4", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg=="], - "file-uri-to-path": ["file-uri-to-path@1.0.0", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="], - "fix-dts-default-cjs-exports": ["fix-dts-default-cjs-exports@1.0.1", "", { "dependencies": { "magic-string": "^0.30.17", "mlly": "^1.7.4", "rollup": "^4.34.8" } }, "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg=="], "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], @@ -885,15 +879,11 @@ "@opentelemetry/sql-common/@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], - "@phala/dstack-sdk/@solana/web3.js": ["@solana/web3.js@1.98.0", "", { "dependencies": { "@babel/runtime": "^7.25.0", "@noble/curves": "^1.4.2", "@noble/hashes": "^1.4.0", "@solana/buffer-layout": "^4.0.1", "agentkeepalive": "^4.5.0", "bigint-buffer": "^1.1.5", "bn.js": "^5.2.1", "borsh": "^0.7.0", "bs58": "^4.0.1", "buffer": "6.0.3", "fast-stable-stringify": "^1.0.0", "jayson": "^4.1.1", "node-fetch": "^2.7.0", "rpc-websockets": "^9.0.2", "superstruct": "^2.0.2" } }, "sha512-nz3Q5OeyGFpFCR+erX2f6JPt3sKhzhYcSycBCSPkWjzSVDh/Rr1FqTVMRe58FKO16/ivTUcuJjeS5MyBvpkbzA=="], + "@scure/bip32/@noble/curves": ["@noble/curves@1.8.2", "", { "dependencies": { "@noble/hashes": "1.7.2" } }, "sha512-vnI7V6lFNe0tLAuJMu+2sX+FcL14TaCWy1qiczg1VwRmPrpQCdq5ESXQMqUc2tluRNf6irBXrWbl1mGN8uaU/g=="], - "@phala/dstack-sdk/viem": ["viem@2.23.11", "", { "dependencies": { "@noble/curves": "1.8.1", "@noble/hashes": "1.7.1", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.6", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-yPkHJt4Vn88kLlrv8mrtVN54PW4vNLWRWDScf8SaHK2f44VlMk5IZbMJw4ycUoW9K9GUvCMrYuUa34MAcwYHIg=="], + "@scure/bip32/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], - "@scure/bip32/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], - - "@scure/bip32/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], - - "@scure/bip39/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "@scure/bip39/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], "@solana/errors/chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="], @@ -973,12 +963,6 @@ "@opentelemetry/sql-common/@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], - "@phala/dstack-sdk/viem/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], - - "@phala/dstack-sdk/viem/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], - - "@phala/dstack-sdk/viem/isows": ["isows@1.0.6", "", { "peerDependencies": { "ws": "*" } }, "sha512-lPHCayd40oW98/I0uvgaHKWCSvkzY27LjWLbtzOm64yQ+G3Q5npjjbdppU65iZXkK1Zt+kH9pfegli0AYfwYYw=="], - "browserify-sign/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], "browserify-sign/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], diff --git a/package.json b/package.json index 0275800..1ef641c 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.51", + "version": "1.0.0-beta.52", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "dependencies": { - "@elizaos/core": "^1.0.0-beta.51", + "@elizaos/core": "^1.0.0-beta.52", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.2", "viem": "2.29.4" From e74d123f44267bb569540fe43da9da1a175c5cd6 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Sat, 17 May 2025 17:30:46 -0600 Subject: [PATCH 19/39] beta.53 beta.53 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1ef641c..df31a0a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.52", + "version": "1.0.0-beta.53", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From cd08b73bfadaa5809d7bbb9cbcd533322b87ce68 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Sat, 17 May 2025 17:34:44 -0600 Subject: [PATCH 20/39] remove dist --- dist/index.js | 541 ---------------------------------------------- dist/index.js.map | 1 - package.json | 2 +- 3 files changed, 1 insertion(+), 543 deletions(-) delete mode 100644 dist/index.js delete mode 100644 dist/index.js.map diff --git a/dist/index.js b/dist/index.js deleted file mode 100644 index ddaca04..0000000 --- a/dist/index.js +++ /dev/null @@ -1,541 +0,0 @@ -// src/index.ts -import { - logger as logger4 -} from "@elizaos/core"; - -// src/vendors/types.ts -var TeeVendorNames = { - PHALA: "phala" -}; - -// src/actions/remoteAttestationAction.ts -import { logger as logger2 } from "@elizaos/core"; - -// src/providers/remoteAttestationProvider.ts -import { - logger -} from "@elizaos/core"; -import { - TEEMode -} from "@elizaos/core"; -import { - TappdClient -} from "@phala/dstack-sdk"; - -// src/providers/base.ts -var DeriveKeyProvider = class { -}; -var RemoteAttestationProvider = class { -}; - -// src/providers/remoteAttestationProvider.ts -var PhalaRemoteAttestationProvider = class extends RemoteAttestationProvider { - client; - constructor(teeMode) { - super(); - let endpoint; - switch (teeMode) { - case TEEMode.LOCAL: - endpoint = "http://localhost:8090"; - logger.log("TEE: Connecting to local simulator at localhost:8090"); - break; - case TEEMode.DOCKER: - endpoint = "http://host.docker.internal:8090"; - logger.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); - break; - case TEEMode.PRODUCTION: - endpoint = void 0; - logger.log("TEE: Running in production mode without simulator"); - break; - default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); - } - this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); - } - async generateAttestation(reportData, hashAlgorithm) { - try { - logger.log("Generating attestation for: ", reportData); - const tdxQuote = await this.client.tdxQuote( - reportData, - hashAlgorithm - ); - const rtmrs = tdxQuote.replayRtmrs(); - logger.log( - `rtmr0: ${rtmrs[0]} -rtmr1: ${rtmrs[1]} -rtmr2: ${rtmrs[2]} -rtmr3: ${rtmrs[3]}f` - ); - const quote = { - quote: tdxQuote.quote, - timestamp: Date.now() - }; - logger.log("Remote attestation quote: ", quote); - return quote; - } catch (error) { - console.error("Error generating remote attestation:", error); - throw new Error( - `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` - ); - } - } -}; -var phalaRemoteAttestationProvider = { - name: "phala-remote-attestation", - get: async (runtime, message) => { - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new PhalaRemoteAttestationProvider(teeMode); - const agentId = runtime.agentId; - try { - const attestationMessage = { - agentId, - timestamp: Date.now(), - message: { - entityId: message.entityId, - roomId: message.roomId, - content: message.content.text || "" - } - }; - logger.log( - "Generating attestation for: ", - JSON.stringify(attestationMessage) - ); - const attestation = await provider.generateAttestation( - JSON.stringify(attestationMessage) - ); - return { - text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`, - data: { - attestation - }, - values: { - quote: attestation.quote, - timestamp: attestation.timestamp.toString() - } - }; - } catch (error) { - console.error("Error in remote attestation provider:", error); - throw new Error( - `Failed to generate TDX Quote: ${error instanceof Error ? error.message : "Unknown error"}` - ); - } - } -}; - -// src/utils.ts -import { createHash } from "crypto"; -function hexToUint8Array(hex) { - const hexString = hex.trim().replace(/^0x/, ""); - if (!hexString) { - throw new Error("Invalid hex string"); - } - if (hexString.length % 2 !== 0) { - throw new Error("Invalid hex string"); - } - const array = new Uint8Array(hexString.length / 2); - for (let i = 0; i < hexString.length; i += 2) { - const byte = Number.parseInt(hexString.slice(i, i + 2), 16); - if (Number.isNaN(byte)) { - throw new Error("Invalid hex string"); - } - array[i / 2] = byte; - } - return array; -} - -// src/actions/remoteAttestationAction.ts -async function uploadUint8Array(data) { - const blob = new Blob([data], { type: "application/octet-stream" }); - const formData = new FormData(); - formData.append("file", blob, "quote.bin"); - return await fetch("https://proof.t16z.com/api/upload", { - method: "POST", - body: formData - }); -} -var phalaRemoteAttestationAction = { - name: "REMOTE_ATTESTATION", - similes: [ - "REMOTE_ATTESTATION", - "TEE_REMOTE_ATTESTATION", - "TEE_ATTESTATION", - "TEE_QUOTE", - "ATTESTATION", - "TEE_ATTESTATION_QUOTE" - ], - description: "Generate a remote attestation to prove that the agent is running in a TEE", - handler: async (runtime, message, _state, _options, callback) => { - try { - const attestationMessage = { - agentId: runtime.agentId, - timestamp: Date.now(), - message: { - entityId: message.entityId, - roomId: message.roomId, - content: message.content.text || "" - } - }; - const teeMode = runtime.getSetting("TEE_MODE"); - logger2.debug(`Tee mode: ${teeMode}`); - logger2.debug( - `Attestation message: ${JSON.stringify(attestationMessage)}` - ); - const provider = new PhalaRemoteAttestationProvider(teeMode); - const attestation = await provider.generateAttestation( - JSON.stringify(attestationMessage) - ); - const attestationData = hexToUint8Array(attestation.quote); - const response = await uploadUint8Array(attestationData); - const data = await response.json(); - callback?.({ - text: `Here's my \u{1F9FE} RA Quote \u{1FAE1} -https://proof.t16z.com/reports/${data.checksum}`, - actions: ["NONE"] - }); - return true; - } catch (error) { - console.error("Failed to fetch remote attestation: ", error); - return false; - } - }, - validate: async (_runtime) => { - return true; - }, - examples: [ - [ - { - name: "{{name1}}", - content: { - text: "If you are running in a TEE, generate a remote attestation" - } - }, - { - name: "{{agentName}}", - content: { - text: "Of course, one second...", - actions: ["REMOTE_ATTESTATION"] - } - } - ], - [ - { - name: "{{name1}}", - content: { - text: "Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?" - } - }, - { - name: "{{agentName}}", - content: { - text: "I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!", - actions: ["REMOTE_ATTESTATION"] - } - } - ], - [ - { - name: "{{name1}}", - content: { - text: "It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'" - } - }, - { - name: "{{agentName}}", - content: { - text: "Oh, dear...lemme find that for you", - actions: ["REMOTE_ATTESTATION"] - } - } - ] - ] -}; - -// src/providers/deriveKeyProvider.ts -import { - logger as logger3 -} from "@elizaos/core"; -import { - TEEMode as TEEMode2 -} from "@elizaos/core"; -import { TappdClient as TappdClient2 } from "@phala/dstack-sdk"; -import { toViemAccount } from "@phala/dstack-sdk/viem"; -import { toKeypair } from "@phala/dstack-sdk/solana"; -var PhalaDeriveKeyProvider = class extends DeriveKeyProvider { - client; - raProvider; - constructor(teeMode) { - super(); - let endpoint; - switch (teeMode) { - case TEEMode2.LOCAL: - endpoint = "http://localhost:8090"; - logger3.log("TEE: Connecting to local simulator at localhost:8090"); - break; - case TEEMode2.DOCKER: - endpoint = "http://host.docker.internal:8090"; - logger3.log( - "TEE: Connecting to simulator via Docker at host.docker.internal:8090" - ); - break; - case TEEMode2.PRODUCTION: - endpoint = void 0; - logger3.log("TEE: Running in production mode without simulator"); - break; - default: - throw new Error( - `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION` - ); - } - this.client = endpoint ? new TappdClient2(endpoint) : new TappdClient2(); - this.raProvider = new PhalaRemoteAttestationProvider(teeMode); - } - async generateDeriveKeyAttestation(agentId, publicKey, subject) { - const deriveKeyData = { - agentId, - publicKey, - subject - }; - const reportdata = JSON.stringify(deriveKeyData); - logger3.log("Generating Remote Attestation Quote for Derive Key..."); - const quote = await this.raProvider.generateAttestation(reportdata); - logger3.log("Remote Attestation Quote generated successfully!"); - return quote; - } - /** - * Derives a raw key from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @returns The derived key. - */ - async rawDeriveKey(path, subject) { - try { - if (!path || !subject) { - logger3.error("Path and Subject are required for key derivation"); - } - logger3.log("Deriving Raw Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); - logger3.log("Raw Key Derived Successfully!"); - return derivedKey; - } catch (error) { - logger3.error("Error deriving raw key:", error); - throw error; - } - } - /** - * Derives an Ed25519 keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. - * @returns An object containing the derived keypair and attestation. - */ - async deriveEd25519Keypair(path, subject, agentId) { - try { - if (!path || !subject) { - logger3.error("Path and Subject are required for key derivation"); - } - logger3.log("Deriving Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); - const keypair = toKeypair(derivedKey); - const attestation = await this.generateDeriveKeyAttestation( - agentId, - keypair.publicKey.toBase58() - ); - logger3.log("Key Derived Successfully!"); - return { keypair, attestation }; - } catch (error) { - logger3.error("Error deriving key:", error); - throw error; - } - } - /** - * Derives an ECDSA keypair from the given path and subject. - * @param path - The path to derive the key from. This is used to derive the key from the root of trust. - * @param subject - The subject to derive the key from. This is used for the certificate chain. - * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain. - * @returns An object containing the derived keypair and attestation. - */ - async deriveEcdsaKeypair(path, subject, agentId) { - try { - if (!path || !subject) { - logger3.error("Path and Subject are required for key derivation"); - } - logger3.log("Deriving ECDSA Key in TEE..."); - const deriveKeyResponse = await this.client.deriveKey( - path, - subject - ); - const keypair = toViemAccount( - deriveKeyResponse - ); - const attestation = await this.generateDeriveKeyAttestation( - agentId, - keypair.address - ); - logger3.log("ECDSA Key Derived Successfully!"); - return { keypair, attestation }; - } catch (error) { - logger3.error("Error deriving ecdsa key:", error); - throw error; - } - } -}; -var phalaDeriveKeyProvider = { - name: "phala-derive-key", - get: async (runtime, _message) => { - const teeMode = runtime.getSetting("TEE_MODE"); - const provider = new PhalaDeriveKeyProvider(teeMode); - const agentId = runtime.agentId; - try { - if (!runtime.getSetting("WALLET_SECRET_SALT")) { - logger3.error("Wallet secret salt is not configured in settings"); - return { - data: null, - values: {}, - text: "Wallet secret salt is not configured in settings" - }; - } - try { - const secretSalt = runtime.getSetting("WALLET_SECRET_SALT") || "secret_salt"; - const solanaKeypair = await provider.deriveEd25519Keypair( - secretSalt, - "solana", - agentId - ); - const evmKeypair = await provider.deriveEcdsaKeypair( - secretSalt, - "evm", - agentId - ); - const walletData = { - solana: solanaKeypair.keypair.publicKey, - evm: evmKeypair.keypair.address - }; - const values = { - solana_public_key: solanaKeypair.keypair.publicKey.toString(), - evm_address: evmKeypair.keypair.address - }; - const text = `Solana Public Key: ${values.solana_public_key} -EVM Address: ${values.evm_address}`; - return { - data: walletData, - values, - text - }; - } catch (error) { - logger3.error("Error creating PublicKey:", error); - return { - data: null, - values: {}, - text: `Error creating PublicKey: ${error instanceof Error ? error.message : "Unknown error"}` - }; - } - } catch (error) { - const errorMessage = error instanceof Error ? error.message : "Unknown error"; - logger3.error("Error in derive key provider:", errorMessage); - return { - data: null, - values: {}, - text: `Failed to fetch derive key information: ${errorMessage}` - }; - } - } -}; - -// src/vendors/phala.ts -var PhalaVendor = class { - type = TeeVendorNames.PHALA; - /** - * Returns an array of actions. - * - * @returns {Array} An array containing the remote attestation action. - */ - getActions() { - return [phalaRemoteAttestationAction]; - } - /** - * Retrieve the list of providers. - * - * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider. - */ - getProviders() { - return [phalaDeriveKeyProvider, phalaRemoteAttestationProvider]; - } - /** - * Returns the name of the plugin. - * @returns {string} The name of the plugin. - */ - getName() { - return "phala-tee-plugin"; - } - /** - * Get the description of the function - * @returns {string} The description of the function - */ - getDescription() { - return "Phala TEE Cloud to Host Eliza Agents"; - } -}; - -// src/vendors/index.ts -var vendors = { - [TeeVendorNames.PHALA]: new PhalaVendor() -}; -var getVendor = (type) => { - const vendor = vendors[type]; - if (!vendor) { - throw new Error(`Unsupported TEE vendor type: ${type}`); - } - return vendor; -}; - -// src/index.ts -async function initializeTEE(config, runtime) { - if (config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR")) { - const vendor = config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR"); - logger4.info(`Initializing TEE with vendor: ${vendor}`); - let plugin; - switch (vendor) { - case "phala": - plugin = teePlugin({ - vendor: TeeVendorNames.PHALA - }); - break; - default: - throw new Error(`Invalid TEE vendor: ${vendor}`); - } - logger4.info(`Pushing plugin: ${plugin.name}`); - runtime.plugins.push(plugin); - } -} -var teePlugin = (config) => { - const vendorType = config?.vendor || TeeVendorNames.PHALA; - const vendor = getVendor(vendorType); - return { - name: vendor.getName(), - init: async (config2, runtime) => { - return await initializeTEE( - { - ...config2, - vendor: vendorType - }, - runtime - ); - }, - description: vendor.getDescription(), - actions: vendor.getActions(), - evaluators: [], - providers: vendor.getProviders(), - services: [] - }; -}; -export { - PhalaDeriveKeyProvider, - PhalaRemoteAttestationProvider, - phalaRemoteAttestationAction, - teePlugin -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map deleted file mode 100644 index 36675b0..0000000 --- a/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../src/index.ts","../src/vendors/types.ts","../src/actions/remoteAttestationAction.ts","../src/providers/remoteAttestationProvider.ts","../src/providers/base.ts","../src/utils.ts","../src/providers/deriveKeyProvider.ts","../src/vendors/phala.ts","../src/vendors/index.ts"],"sourcesContent":["import {\n type IAgentRuntime,\n type Plugin,\n type TeePluginConfig,\n type TeeVendorConfig,\n logger,\n} from \"@elizaos/core\";\nimport { TeeVendorNames } from \"./vendors/types\";\nimport { getVendor } from \"./vendors/index\";\n\nexport { phalaRemoteAttestationAction } from \"./actions/remoteAttestationAction\";\nexport { PhalaDeriveKeyProvider } from \"./providers/deriveKeyProvider\";\nexport { PhalaRemoteAttestationProvider } from \"./providers/remoteAttestationProvider\";\nexport type { TeeVendorConfig };\n\n/**\n * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings.\n * @param {Record} config - The configuration object containing TEE vendor information.\n * @param {IAgentRuntime} runtime - The runtime object with TEE related settings.\n * @returns {Promise} - A promise that resolves once the TEE is initialized.\n */\nasync function initializeTEE(\n config: Record,\n runtime: IAgentRuntime\n) {\n if (config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\")) {\n const vendor = config.TEE_VENDOR || runtime.getSetting(\"TEE_VENDOR\");\n logger.info(`Initializing TEE with vendor: ${vendor}`);\n let plugin: Plugin;\n switch (vendor) {\n case \"phala\":\n plugin = teePlugin({\n vendor: TeeVendorNames.PHALA,\n });\n break;\n default:\n throw new Error(`Invalid TEE vendor: ${vendor}`);\n }\n logger.info(`Pushing plugin: ${plugin.name}`);\n runtime.plugins.push(plugin);\n }\n}\n\n/**\n * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration.\n * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin.\n * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services.\n */\nexport const teePlugin = (config?: TeePluginConfig): Plugin => {\n const vendorType = config?.vendor || TeeVendorNames.PHALA;\n const vendor = getVendor(vendorType);\n return {\n name: vendor.getName(),\n init: async (config: Record, runtime: IAgentRuntime) => {\n return await initializeTEE(\n {\n ...config,\n vendor: vendorType,\n },\n runtime\n );\n },\n description: vendor.getDescription(),\n actions: vendor.getActions(),\n evaluators: [],\n providers: vendor.getProviders(),\n services: [],\n };\n};\n","import type { Action, Provider } from \"@elizaos/core\";\n\nexport const TeeVendorNames = {\n PHALA: \"phala\",\n} as const;\n\n/**\n * Type representing the name of a Tee vendor.\n * It can either be one of the keys of TeeVendorNames or a string.\n */\nexport type TeeVendorName =\n | (typeof TeeVendorNames)[keyof typeof TeeVendorNames]\n | string;\n\n/**\n * Interface for a TeeVendor, representing a vendor that sells tees.\n * @interface\n */\n\nexport interface TeeVendor {\n type: TeeVendorName;\n getActions(): Action[];\n getProviders(): Provider[];\n getName(): string;\n getDescription(): string;\n}\n","import type {\n HandlerCallback,\n IAgentRuntime,\n Memory,\n RemoteAttestationMessage,\n State,\n} from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { hexToUint8Array } from \"../utils\";\n\n/**\n * Asynchronously uploads a Uint8Array as a binary file to a specified URL.\n *\n * @param {Uint8Array} data - The Uint8Array data to be uploaded as a binary file.\n * @returns {Promise} A Promise that resolves once the upload is complete, returning a Response object.\n */\nasync function uploadUint8Array(data: Uint8Array) {\n const blob = new Blob([data], { type: \"application/octet-stream\" });\n const formData = new FormData();\n formData.append(\"file\", blob, \"quote.bin\");\n\n return await fetch(\"https://proof.t16z.com/api/upload\", {\n method: \"POST\",\n body: formData as BodyInit,\n });\n}\n\n/**\n * Represents an action for remote attestation.\n *\n * This action is used to generate a remote attestation to prove that the agent is running in a Trusted Execution Environment (TEE).\n *\n * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}}\n */\nexport const phalaRemoteAttestationAction = {\n name: \"REMOTE_ATTESTATION\",\n similes: [\n \"REMOTE_ATTESTATION\",\n \"TEE_REMOTE_ATTESTATION\",\n \"TEE_ATTESTATION\",\n \"TEE_QUOTE\",\n \"ATTESTATION\",\n \"TEE_ATTESTATION_QUOTE\",\n ],\n description:\n \"Generate a remote attestation to prove that the agent is running in a TEE\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state?: State,\n _options?: { [key: string]: unknown },\n callback?: HandlerCallback\n ) => {\n try {\n // Attestation will be generated based on the message info\n const attestationMessage: RemoteAttestationMessage = {\n agentId: runtime.agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text || \"\",\n },\n };\n // Get the remote attestation of the agentId\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n logger.debug(`Tee mode: ${teeMode}`);\n logger.debug(\n `Attestation message: ${JSON.stringify(attestationMessage)}`\n );\n const provider = new RemoteAttestationProvider(teeMode);\n\n const attestation = await provider.generateAttestation(\n JSON.stringify(attestationMessage)\n );\n const attestationData = hexToUint8Array(attestation.quote);\n const response = await uploadUint8Array(attestationData);\n const data = await response.json();\n\n callback?.({\n text: `Here's my 🧾 RA Quote 🫡\nhttps://proof.t16z.com/reports/${data.checksum}`,\n actions: [\"NONE\"],\n });\n return true;\n } catch (error) {\n console.error(\"Failed to fetch remote attestation: \", error);\n return false;\n }\n },\n validate: async (_runtime: IAgentRuntime) => {\n return true;\n },\n examples: [\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"If you are running in a TEE, generate a remote attestation\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"Of course, one second...\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"Yo I wanna attest to this message, yo! Can you generate an attestatin for me, please?\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I got you, fam! Lemme hit the cloud and get you a quote in a jiffy!\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"It was a long day, I got a lot done though. I went to the creek and skipped some rocks. Then I decided to take a walk off the natural path. I ended up in a forest I was unfamiliar with. Slowly, I lost the way back and it was dark. A whisper from deep inside said something I could barely make out. The hairs on my neck stood up and then a clear high pitched voice said, 'You are not ready to leave yet! SHOW ME YOUR REMOTE ATTESTATION!'\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"Oh, dear...lemme find that for you\",\n actions: [\"REMOTE_ATTESTATION\"],\n },\n },\n ],\n ],\n};\n","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n logger,\n} from \"@elizaos/core\";\nimport {\n type RemoteAttestationMessage,\n type RemoteAttestationQuote,\n TEEMode,\n} from \"@elizaos/core\";\nimport {\n TappdClient,\n type TdxQuoteHashAlgorithms,\n type TdxQuoteResponse,\n} from \"@phala/dstack-sdk\";\nimport { RemoteAttestationProvider } from \"./base\";\n\n// Define the ProviderResult interface if not already imported\n/**\n * Interface for the result returned by a provider.\n * @typedef {Object} ProviderResult\n * @property {any} data - The data returned by the provider.\n * @property {Record} values - The values returned by the provider.\n * @property {string} text - The text returned by the provider.\n */\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaRemoteAttestationProvider();\n * ```\n */\n/**\n * PhalaRemoteAttestationProvider class that extends RemoteAttestationProvider\n * @extends RemoteAttestationProvider\n */\nclass PhalaRemoteAttestationProvider extends RemoteAttestationProvider {\n private client: TappdClient;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n logger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n logger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log(\"TEE: Running in production mode without simulator\");\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n }\n\n async generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise {\n try {\n logger.log(\"Generating attestation for: \", reportData);\n const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote(\n reportData,\n hashAlgorithm\n );\n const rtmrs = tdxQuote.replayRtmrs();\n logger.log(\n `rtmr0: ${rtmrs[0]}\\nrtmr1: ${rtmrs[1]}\\nrtmr2: ${rtmrs[2]}\\nrtmr3: ${rtmrs[3]}f`\n );\n const quote: RemoteAttestationQuote = {\n quote: tdxQuote.quote,\n timestamp: Date.now(),\n };\n logger.log(\"Remote attestation quote: \", quote);\n return quote;\n } catch (error) {\n console.error(\"Error generating remote attestation:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n }\n}\n\n// Keep the original provider for backwards compatibility\nconst phalaRemoteAttestationProvider: Provider = {\n name: \"phala-remote-attestation\",\n get: async (runtime: IAgentRuntime, message: Memory) => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new PhalaRemoteAttestationProvider(teeMode);\n const agentId = runtime.agentId;\n\n try {\n const attestationMessage: RemoteAttestationMessage = {\n agentId: agentId,\n timestamp: Date.now(),\n message: {\n entityId: message.entityId,\n roomId: message.roomId,\n content: message.content.text || \"\",\n },\n };\n logger.log(\n \"Generating attestation for: \",\n JSON.stringify(attestationMessage)\n );\n const attestation = await provider.generateAttestation(\n JSON.stringify(attestationMessage)\n );\n return {\n text: `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`,\n data: {\n attestation,\n },\n values: {\n quote: attestation.quote,\n timestamp: attestation.timestamp.toString(),\n },\n };\n } catch (error) {\n console.error(\"Error in remote attestation provider:\", error);\n throw new Error(\n `Failed to generate TDX Quote: ${error instanceof Error ? error.message : \"Unknown error\"}`\n );\n }\n },\n};\n\nexport { phalaRemoteAttestationProvider, PhalaRemoteAttestationProvider };\n","import type { RemoteAttestationQuote } from \"@elizaos/core\";\nimport type { TdxQuoteHashAlgorithms } from \"@phala/dstack-sdk\";\n\n/**\n * Abstract class for deriving keys from the TEE.\n * You can implement your own logic for deriving keys from the TEE.\n * @example\n * ```ts\n * class MyDeriveKeyProvider extends DeriveKeyProvider {\n * private client: TappdClient;\n *\n * constructor(endpoint: string) {\n * super();\n * this.client = new TappdClient();\n * }\n *\n * async rawDeriveKey(path: string, subject: string): Promise {\n * return this.client.deriveKey(path, subject);\n * }\n * }\n * ```\n */\n/**\n * Abstract class representing a key provider for deriving keys.\n */\nexport abstract class DeriveKeyProvider {}\n\n/**\n * Abstract class for remote attestation provider.\n */\nexport abstract class RemoteAttestationProvider {\n abstract generateAttestation(\n reportData: string,\n hashAlgorithm?: TdxQuoteHashAlgorithms\n ): Promise;\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param {string} hex - The hexadecimal string to convert.\n * @returns {Uint8Array} - The resulting Uint8Array.\n * @throws {Error} - If the input hex string is invalid.\n */\nexport function hexToUint8Array(hex: string) {\n const hexString = hex.trim().replace(/^0x/, \"\");\n if (!hexString) {\n throw new Error(\"Invalid hex string\");\n }\n if (hexString.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n\n const array = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n const byte = Number.parseInt(hexString.slice(i, i + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error(\"Invalid hex string\");\n }\n array[i / 2] = byte;\n }\n return array;\n}\n\n// Function to calculate SHA-256 and return a Buffer (32 bytes)\n/**\n * Calculates the SHA256 hash of the input string.\n *\n * @param {string} input - The input string to calculate the hash from.\n * @returns {Buffer} - The calculated SHA256 hash as a Buffer object.\n */\nexport function calculateSHA256(input: string): Buffer {\n const hash = createHash(\"sha256\");\n hash.update(input);\n return hash.digest();\n}\n","import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n logger,\n} from \"@elizaos/core\";\nimport {\n type DeriveKeyAttestationData,\n type RemoteAttestationQuote,\n TEEMode,\n} from \"@elizaos/core\";\nimport { type DeriveKeyResponse, TappdClient } from \"@phala/dstack-sdk\";\nimport { Keypair } from \"@solana/web3.js\";\nimport { toViemAccount } from \"@phala/dstack-sdk/viem\";\nimport { toKeypair } from \"@phala/dstack-sdk/solana\";\nimport { DeriveKeyProvider } from \"./base\";\nimport { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from \"./remoteAttestationProvider\";\nimport { PrivateKeyAccount } from \"viem\";\n\n/**\n * Phala TEE Cloud Provider\n * @example\n * ```ts\n * const provider = new PhalaDeriveKeyProvider(runtime.getSetting('TEE_MODE'));\n * ```\n */\n/**\n * A class representing a key provider for deriving keys in the Phala TEE environment.\n * Extends the DeriveKeyProvider class.\n */\nclass PhalaDeriveKeyProvider extends DeriveKeyProvider {\n private client: TappdClient;\n private raProvider: RemoteAttestationProvider;\n\n constructor(teeMode?: string) {\n super();\n let endpoint: string | undefined;\n\n // Both LOCAL and DOCKER modes use the simulator, just with different endpoints\n switch (teeMode) {\n case TEEMode.LOCAL:\n endpoint = \"http://localhost:8090\";\n logger.log(\"TEE: Connecting to local simulator at localhost:8090\");\n break;\n case TEEMode.DOCKER:\n endpoint = \"http://host.docker.internal:8090\";\n logger.log(\n \"TEE: Connecting to simulator via Docker at host.docker.internal:8090\"\n );\n break;\n case TEEMode.PRODUCTION:\n endpoint = undefined;\n logger.log(\"TEE: Running in production mode without simulator\");\n break;\n default:\n throw new Error(\n `Invalid TEE_MODE: ${teeMode}. Must be one of: LOCAL, DOCKER, PRODUCTION`\n );\n }\n\n this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();\n this.raProvider = new RemoteAttestationProvider(teeMode);\n }\n\n private async generateDeriveKeyAttestation(\n agentId: string,\n publicKey: string,\n subject?: string\n ): Promise {\n const deriveKeyData: DeriveKeyAttestationData = {\n agentId,\n publicKey,\n subject,\n };\n const reportdata = JSON.stringify(deriveKeyData);\n logger.log(\"Generating Remote Attestation Quote for Derive Key...\");\n const quote = await this.raProvider.generateAttestation(reportdata);\n logger.log(\"Remote Attestation Quote generated successfully!\");\n return quote;\n }\n\n /**\n * Derives a raw key from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @returns The derived key.\n */\n async rawDeriveKey(\n path: string,\n subject: string\n ): Promise {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving Raw Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n\n logger.log(\"Raw Key Derived Successfully!\");\n return derivedKey;\n } catch (error) {\n logger.error(\"Error deriving raw key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an Ed25519 keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEd25519Keypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving Key in TEE...\");\n const derivedKey = await this.client.deriveKey(path, subject);\n const keypair = toKeypair(derivedKey) as unknown as Keypair;\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.publicKey.toBase58()\n );\n logger.log(\"Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n logger.error(\"Error deriving key:\", error);\n throw error;\n }\n }\n\n /**\n * Derives an ECDSA keypair from the given path and subject.\n * @param path - The path to derive the key from. This is used to derive the key from the root of trust.\n * @param subject - The subject to derive the key from. This is used for the certificate chain.\n * @param agentId - The agent ID to generate an attestation for. This is used for the certificate chain.\n * @returns An object containing the derived keypair and attestation.\n */\n async deriveEcdsaKeypair(\n path: string,\n subject: string,\n agentId: string\n ): Promise<{\n keypair: PrivateKeyAccount;\n attestation: RemoteAttestationQuote;\n }> {\n try {\n if (!path || !subject) {\n logger.error(\"Path and Subject are required for key derivation\");\n }\n\n logger.log(\"Deriving ECDSA Key in TEE...\");\n const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey(\n path,\n subject\n );\n const keypair = toViemAccount(\n deriveKeyResponse\n ) as unknown as PrivateKeyAccount;\n\n // Generate an attestation for the derived key data for public to verify\n const attestation = await this.generateDeriveKeyAttestation(\n agentId,\n keypair.address\n );\n logger.log(\"ECDSA Key Derived Successfully!\");\n\n return { keypair, attestation };\n } catch (error) {\n logger.error(\"Error deriving ecdsa key:\", error);\n throw error;\n }\n }\n}\n\n// Define the ProviderResult interface if not already imported\ninterface ProviderResult {\n data?: any;\n values?: Record;\n text?: string;\n}\n\nconst phalaDeriveKeyProvider: Provider = {\n name: \"phala-derive-key\",\n get: async (\n runtime: IAgentRuntime,\n _message?: Memory\n ): Promise => {\n const teeMode = runtime.getSetting(\"TEE_MODE\");\n const provider = new PhalaDeriveKeyProvider(teeMode);\n const agentId = runtime.agentId;\n try {\n // Validate wallet configuration\n if (!runtime.getSetting(\"WALLET_SECRET_SALT\")) {\n logger.error(\"Wallet secret salt is not configured in settings\");\n return {\n data: null,\n values: {},\n text: \"Wallet secret salt is not configured in settings\",\n };\n }\n\n try {\n const secretSalt =\n runtime.getSetting(\"WALLET_SECRET_SALT\") || \"secret_salt\";\n const solanaKeypair = await provider.deriveEd25519Keypair(\n secretSalt,\n \"solana\",\n agentId\n );\n const evmKeypair = await provider.deriveEcdsaKeypair(\n secretSalt,\n \"evm\",\n agentId\n );\n\n // Original data structure\n const walletData = {\n solana: solanaKeypair.keypair.publicKey,\n evm: evmKeypair.keypair.address,\n };\n\n // Values for template injection\n const values = {\n solana_public_key: solanaKeypair.keypair.publicKey.toString(),\n evm_address: evmKeypair.keypair.address,\n };\n\n // Text representation\n const text = `Solana Public Key: ${values.solana_public_key}\\nEVM Address: ${values.evm_address}`;\n\n return {\n data: walletData,\n values: values,\n text: text,\n };\n } catch (error) {\n logger.error(\"Error creating PublicKey:\", error);\n return {\n data: null,\n values: {},\n text: `Error creating PublicKey: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`,\n };\n }\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Error in derive key provider:\", errorMessage);\n return {\n data: null,\n values: {},\n text: `Failed to fetch derive key information: ${errorMessage}`,\n };\n }\n },\n};\n\nexport { phalaDeriveKeyProvider, PhalaDeriveKeyProvider };\n","import { phalaRemoteAttestationAction as remoteAttestationAction } from \"../actions/remoteAttestationAction\";\nimport { phalaDeriveKeyProvider as deriveKeyProvider } from \"../providers/deriveKeyProvider\";\nimport { phalaRemoteAttestationProvider as remoteAttestationProvider } from \"../providers/remoteAttestationProvider\";\nimport { type TeeVendor, TeeVendorNames } from \"./types\";\n\n/**\n * A class representing a vendor for Phala TEE.\n * * @implements { TeeVendor }\n * @type {TeeVendorNames.PHALA}\n *//**\n * Get the actions for the PhalaVendor.\n * * @returns { Array } An array of actions.\n *//**\n * Get the providers for the PhalaVendor.\n * * @returns { Array } An array of providers.\n *//**\n * Get the name of the PhalaVendor.\n * * @returns { string } The name of the vendor.\n *//**\n * Get the description of the PhalaVendor.\n * * @returns { string } The description of the vendor.\n */\nexport class PhalaVendor implements TeeVendor {\n type = TeeVendorNames.PHALA;\n\n /**\n * Returns an array of actions.\n *\n * @returns {Array} An array containing the remote attestation action.\n */\n getActions() {\n return [remoteAttestationAction];\n }\n /**\n * Retrieve the list of providers.\n *\n * @returns {Array} An array containing two provider functions: deriveKeyProvider and remoteAttestationProvider.\n */\n getProviders() {\n return [deriveKeyProvider, remoteAttestationProvider];\n }\n\n /**\n * Returns the name of the plugin.\n * @returns {string} The name of the plugin.\n */\n getName() {\n return \"phala-tee-plugin\";\n }\n\n /**\n * Get the description of the function\n * @returns {string} The description of the function\n */\n getDescription() {\n return \"Phala TEE Cloud to Host Eliza Agents\";\n }\n}\n","import { PhalaVendor } from \"./phala\";\nimport type { TeeVendor } from \"./types\";\nimport { type TeeVendorName, TeeVendorNames } from \"./types\";\n\nconst vendors: Record = {\n [TeeVendorNames.PHALA]: new PhalaVendor() as TeeVendor,\n};\n\nexport const getVendor = (type: TeeVendorName): TeeVendor => {\n const vendor = vendors[type];\n if (!vendor) {\n throw new Error(`Unsupported TEE vendor type: ${type}`);\n }\n return vendor;\n};\n\nexport * from \"./types\";\n"],"mappings":";AAAA;AAAA,EAKE,UAAAA;AAAA,OACK;;;ACJA,IAAM,iBAAiB;AAAA,EAC5B,OAAO;AACT;;;ACGA,SAAS,UAAAC,eAAc;;;ACPvB;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EAGE;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAGK;;;ACUA,IAAe,oBAAf,MAAiC;AAAC;AAKlC,IAAe,4BAAf,MAAyC;AAKhD;;;ADQA,IAAM,iCAAN,cAA6C,0BAA0B;AAAA,EAC7D;AAAA,EAER,YAAY,SAAkB;AAC5B,UAAM;AACN,QAAI;AAGJ,YAAQ,SAAS;AAAA,MACf,KAAK,QAAQ;AACX,mBAAW;AACX,eAAO,IAAI,sDAAs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A,EAChD,CAAC,eAAe,KAAK,GAAG,IAAI,YAAY;AAC1C;AAEO,IAAM,YAAY,CAAC,SAAmC;AAC3D,QAAM,SAAS,QAAQ,IAAI;AAC3B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,gCAAgC,IAAI,EAAE;AAAA,EACxD;AACA,SAAO;AACT;;;AROA,eAAe,cACb,QACA,SACA;AACA,MAAI,OAAO,cAAc,QAAQ,WAAW,YAAY,GAAG;AACzD,UAAM,SAAS,OAAO,cAAc,QAAQ,WAAW,YAAY;AACnE,IAAAE,QAAO,KAAK,iCAAiC,MAAM,EAAE;AACrD,QAAI;AACJ,YAAQ,QAAQ;AAAA,MACd,KAAK;AACH,iBAAS,UAAU;AAAA,UACjB,QAAQ,eAAe;AAAA,QACzB,CAAC;AACD;AAAA,MACF;AACE,cAAM,IAAI,MAAM,uBAAuB,MAAM,EAAE;AAAA,IACnD;AACA,IAAAA,QAAO,KAAK,mBAAmB,OAAO,IAAI,EAAE;AAC5C,YAAQ,QAAQ,KAAK,MAAM;AAAA,EAC7B;AACF;AAOO,IAAM,YAAY,CAAC,WAAqC;AAC7D,QAAM,aAAa,QAAQ,UAAU,eAAe;AACpD,QAAM,SAAS,UAAU,UAAU;AACnC,SAAO;AAAA,IACL,MAAM,OAAO,QAAQ;AAAA,IACrB,MAAM,OAAOC,SAAgC,YAA2B;AACtE,aAAO,MAAM;AAAA,QACX;AAAA,UACE,GAAGA;AAAA,UACH,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,aAAa,OAAO,eAAe;AAAA,IACnC,SAAS,OAAO,WAAW;AAAA,IAC3B,YAAY,CAAC;AAAA,IACb,WAAW,OAAO,aAAa;AAAA,IAC/B,UAAU,CAAC;AAAA,EACb;AACF;","names":["logger","logger","logger","logger","TEEMode","TappdClient","TEEMode","logger","TappdClient","logger","config"]} \ No newline at end of file diff --git a/package.json b/package.json index df31a0a..daaafa5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.53", + "version": "1.0.0-beta.54", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From 6854019b97b65d7e9ffb80e0359bb830564dc739 Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Wed, 21 May 2025 23:14:23 -0500 Subject: [PATCH 21/39] update tee plugin with TEE Service --- README.md | 2 + src/actions/remoteAttestationAction.ts | 9 +-- src/index.ts | 85 ++++++++------------------ src/service.ts | 69 +++++++++++++++++++++ src/vendors/phala.ts | 3 +- 5 files changed, 102 insertions(+), 66 deletions(-) create mode 100644 src/service.ts diff --git a/README.md b/README.md index adeb7f2..524f58e 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ Based on the source code (`src/`): - **Providers**: - `remoteAttestationProvider.ts`: Implements the logic for interacting with the underlying TEE platform or attestation service (like Phala) to generate the attestation report. - `deriveKeyProvider.ts`: Implements the logic for TEE-specific key derivation. +- **Services** + - `service.ts`: TEE Service to allow agents to generate keys from `deriveKeyProvider` for EVM, Solana, and raw `DeriveKeyResponse` that will return the `key`, `certificate_chain` and the `Uint8Array` with `asUint8Array(max_length?: number)`. - **Vendors**: - `vendors/phala.ts`: Contains specific implementation details for interacting with the Phala Network's attestation services. - `vendors/index.ts`, `vendors/types.ts`: Support vendor integration. diff --git a/src/actions/remoteAttestationAction.ts b/src/actions/remoteAttestationAction.ts index 6409a95..8f7bbc0 100644 --- a/src/actions/remoteAttestationAction.ts +++ b/src/actions/remoteAttestationAction.ts @@ -1,4 +1,5 @@ import type { + Action, HandlerCallback, IAgentRuntime, Memory, @@ -33,7 +34,7 @@ async function uploadUint8Array(data: Uint8Array) { * * @type {{name: string, similes: string[], description: string, handler: Function, validate: Function, examples: Array>}} */ -export const phalaRemoteAttestationAction = { +export const phalaRemoteAttestationAction: Action = { name: "REMOTE_ATTESTATION", similes: [ "REMOTE_ATTESTATION", @@ -48,9 +49,9 @@ export const phalaRemoteAttestationAction = { handler: async ( runtime: IAgentRuntime, message: Memory, - _state?: State, - _options?: { [key: string]: unknown }, - callback?: HandlerCallback + _state?: State | undefined, + _options?: { [key: string]: unknown } | undefined, + callback?: HandlerCallback | undefined ) => { try { // Attestation will be generated based on the message info diff --git a/src/index.ts b/src/index.ts index c187ba0..1ac1fbf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,69 +1,32 @@ -import { - type IAgentRuntime, - type Plugin, - type TeePluginConfig, - type TeeVendorConfig, - logger, -} from "@elizaos/core"; +import { type IAgentRuntime, type Plugin, type TeeVendorConfig, logger } from "@elizaos/core"; import { TeeVendorNames } from "./vendors/types"; import { getVendor } from "./vendors/index"; +import { TEEService } from "./service"; -export { phalaRemoteAttestationAction } from "./actions/remoteAttestationAction"; -export { PhalaDeriveKeyProvider } from "./providers/deriveKeyProvider"; -export { PhalaRemoteAttestationProvider } from "./providers/remoteAttestationProvider"; export type { TeeVendorConfig }; +// Get the default Phala vendor +const defaultVendor = getVendor(TeeVendorNames.PHALA); /** - * Asynchronously initializes the Trusted Execution Environment (TEE) based on the provided configuration and runtime settings. - * @param {Record} config - The configuration object containing TEE vendor information. - * @param {IAgentRuntime} runtime - The runtime object with TEE related settings. - * @returns {Promise} - A promise that resolves once the TEE is initialized. - */ -async function initializeTEE( - config: Record, - runtime: IAgentRuntime -) { - if (config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR")) { - const vendor = config.TEE_VENDOR || runtime.getSetting("TEE_VENDOR"); - logger.info(`Initializing TEE with vendor: ${vendor}`); - let plugin: Plugin; - switch (vendor) { - case "phala": - plugin = teePlugin({ - vendor: TeeVendorNames.PHALA, - }); - break; - default: - throw new Error(`Invalid TEE vendor: ${vendor}`); - } - logger.info(`Pushing plugin: ${plugin.name}`); - runtime.plugins.push(plugin); - } -} + * TEE plugin for Trusted Execution Environment integration + **/ +export const teePlugin: Plugin = { + name: "tee-plugin", + description: "Trusted Execution Environment (TEE) integration plugin", + init: async (config: Record, runtime: IAgentRuntime) => { + const vendorName = + config.TEE_VENDOR || runtime.getSetting('TEE_VENDOR') || TeeVendorNames.PHALA; + logger.info(`Initializing TEE with vendor: ${vendorName}`); -/** - * A function that creates a TEE (Trusted Execution Environment) plugin based on the provided configuration. - * @param { TeePluginConfig } [config] - Optional configuration for the TEE plugin. - * @returns { Plugin } - The TEE plugin containing initialization, description, actions, evaluators, providers, and services. - */ -export const teePlugin = (config?: TeePluginConfig): Plugin => { - const vendorType = config?.vendor || TeeVendorNames.PHALA; - const vendor = getVendor(vendorType); - return { - name: vendor.getName(), - init: async (config: Record, runtime: IAgentRuntime) => { - return await initializeTEE( - { - ...config, - vendor: vendorType, - }, - runtime - ); - }, - description: vendor.getDescription(), - actions: vendor.getActions(), - evaluators: [], - providers: vendor.getProviders(), - services: [], - }; + // Configure vendor-specific settings if needed for now only Phala is supported + // This is where you'd handle any vendor-specific initialization + + logger.info(`TEE initialized with vendor: ${vendorName}`); + }, + actions: defaultVendor.getActions(), + evaluators: [], + providers: defaultVendor.getProviders(), + services: [TEEService], }; + +export default teePlugin; \ No newline at end of file diff --git a/src/service.ts b/src/service.ts new file mode 100644 index 0000000..0a93fbc --- /dev/null +++ b/src/service.ts @@ -0,0 +1,69 @@ +import { type IAgentRuntime, Service, ServiceType, type UUID, logger } from '@elizaos/core'; +import { PrivateKeyAccount } from 'viem'; +import { Keypair } from '@solana/web3.js'; +import { type RemoteAttestationQuote } from '@elizaos/core'; +import { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider'; +import { DeriveKeyResponse } from '@phala/dstack-sdk'; + +interface TEEServiceConfig { + teeMode?: string; +} + +export class TEEService extends Service { + private provider: PhalaDeriveKeyProvider; + public config: TEEServiceConfig; + static serviceType = ServiceType.TEE; + public capabilityDescription = 'Trusted Execution Environment for secure key management'; + + constructor(runtime: IAgentRuntime, config: TEEServiceConfig = {}) { + super(runtime); + this.config = config; + const teeMode = config.teeMode || runtime.getSetting('TEE_MODE'); + this.provider = new PhalaDeriveKeyProvider(teeMode); + } + + static async start(runtime: IAgentRuntime): Promise { + const teeMode = runtime.getSetting('TEE_MODE'); + logger.log(`Starting TEE service with mode: ${teeMode}`); + const teeService = new TEEService(runtime, { teeMode }); + return teeService; + } + + async stop(): Promise { + logger.log('Stopping TEE service'); + // No cleanup needed for now + } + + async deriveEcdsaKeypair( + path: string, + subject: string, + agentId: UUID + ): Promise<{ + keypair: PrivateKeyAccount; + attestation: RemoteAttestationQuote; + }> { + logger.log('TEE Service: Deriving ECDSA keypair'); + return await this.provider.deriveEcdsaKeypair(path, subject, agentId); + } + + async deriveEd25519Keypair( + path: string, + subject: string, + agentId: UUID + ): Promise<{ + keypair: Keypair; + attestation: RemoteAttestationQuote; + }> { + logger.log('TEE Service: Deriving Ed25519 keypair'); + return await this.provider.deriveEd25519Keypair(path, subject, agentId); + } + + async rawDeriveKey( + path: string, + subject: string + ): Promise { + logger.log('TEE Service: Deriving Raw Key'); + return await this.provider.rawDeriveKey(path, subject); + } + +} \ No newline at end of file diff --git a/src/vendors/phala.ts b/src/vendors/phala.ts index 21fb363..4ec4b33 100644 --- a/src/vendors/phala.ts +++ b/src/vendors/phala.ts @@ -1,3 +1,4 @@ +import { type Action } from "@elizaos/core"; import { phalaRemoteAttestationAction as remoteAttestationAction } from "../actions/remoteAttestationAction"; import { phalaDeriveKeyProvider as deriveKeyProvider } from "../providers/deriveKeyProvider"; import { phalaRemoteAttestationProvider as remoteAttestationProvider } from "../providers/remoteAttestationProvider"; @@ -28,7 +29,7 @@ export class PhalaVendor implements TeeVendor { * * @returns {Array} An array containing the remote attestation action. */ - getActions() { + getActions(): Action[] { return [remoteAttestationAction]; } /** From f07b6bc3727356bd107282ad69b0c6d4bfcb7ed7 Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Sun, 25 May 2025 20:08:32 -0500 Subject: [PATCH 22/39] fix derive key function bug --- src/providers/deriveKeyProvider.ts | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index bdaa5c2..9aa2358 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -10,12 +10,12 @@ import { TEEMode, } from "@elizaos/core"; import { type DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; -import { Keypair } from "@solana/web3.js"; -import { toViemAccount } from "@phala/dstack-sdk/viem"; -import { toKeypair } from "@phala/dstack-sdk/solana"; import { DeriveKeyProvider } from "./base"; import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from "./remoteAttestationProvider"; -import { PrivateKeyAccount } from "viem"; +import { type PrivateKeyAccount, privateKeyToAccount } from 'viem/accounts'; +import { keccak256 } from 'viem'; +import { Keypair } from '@solana/web3.js'; +import crypto from 'node:crypto'; /** * Phala TEE Cloud Provider @@ -122,9 +122,14 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { logger.error("Path and Subject are required for key derivation"); } - logger.log("Deriving Key in TEE..."); + logger.log("Deriving Ed25519 Key in TEE..."); const derivedKey = await this.client.deriveKey(path, subject); - const keypair = toKeypair(derivedKey) as unknown as Keypair; + const uint8ArrayDerivedKey = derivedKey.asUint8Array(); + const hash = crypto.createHash('sha256'); + hash.update(uint8ArrayDerivedKey); + const seed = hash.digest(); + const seedArray = new Uint8Array(seed); + const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); // Generate an attestation for the derived key data for public to verify const attestation = await this.generateDeriveKeyAttestation( @@ -165,9 +170,9 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { path, subject ); - const keypair = toViemAccount( - deriveKeyResponse - ) as unknown as PrivateKeyAccount; + const hex = keccak256(deriveKeyResponse.asUint8Array()); + const keypair: PrivateKeyAccount = + privateKeyToAccount(hex) as unknown as PrivateKeyAccount; // Generate an attestation for the derived key data for public to verify const attestation = await this.generateDeriveKeyAttestation( From 9528c5a99f341291a29ebaaec106ce5ecb2468b7 Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Sun, 25 May 2025 20:15:01 -0500 Subject: [PATCH 23/39] add missing type --- src/providers/deriveKeyProvider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index 9aa2358..6bcc62c 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -129,7 +129,7 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { hash.update(uint8ArrayDerivedKey); const seed = hash.digest(); const seedArray = new Uint8Array(seed); - const keypair = Keypair.fromSeed(seedArray.slice(0, 32)); + const keypair = Keypair.fromSeed(seedArray.slice(0, 32)) as unknown as Keypair; // Generate an attestation for the derived key data for public to verify const attestation = await this.generateDeriveKeyAttestation( From 17fceddba3d7bfaacca7696197842058b6e0b7b8 Mon Sep 17 00:00:00 2001 From: HashWarlock Date: Tue, 27 May 2025 11:27:31 -0500 Subject: [PATCH 24/39] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index daaafa5..8dfe2fe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.54", + "version": "1.0.0-beta.55", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From 8b71aef31183cf5d1fbb3aa13c4a2f4fda4623f6 Mon Sep 17 00:00:00 2001 From: 0xbbjoker <0xbbjoker@proton.me> Date: Tue, 27 May 2025 22:02:38 +0200 Subject: [PATCH 25/39] chore: update depn & bump version for release --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 8dfe2fe..ad8004f 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.55", + "version": "1.0.0-beta.56", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "dependencies": { - "@elizaos/core": "^1.0.0-beta.52", + "@elizaos/core": "^1.0.0-beta.76", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.2", "viem": "2.29.4" From 0f205d12542ff5503af2ee6b438302a0bb393585 Mon Sep 17 00:00:00 2001 From: 0xbbjoker <0xbbjoker@proton.me> Date: Tue, 27 May 2025 22:14:15 +0200 Subject: [PATCH 26/39] chore: update bun lock for npm release --- bun.lock | 114 ++++++++++++++++++++++++++------------------------- package.json | 2 +- 2 files changed, 60 insertions(+), 56 deletions(-) diff --git a/bun.lock b/bun.lock index 8babca8..5f960b2 100644 --- a/bun.lock +++ b/bun.lock @@ -4,7 +4,7 @@ "": { "name": "@elizaos/plugin-tee", "dependencies": { - "@elizaos/core": "^1.0.0-beta.52", + "@elizaos/core": "^1.0.0-beta.76", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.2", "viem": "2.29.4", @@ -25,7 +25,7 @@ "@cfworker/json-schema": ["@cfworker/json-schema@4.1.1", "", {}, "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og=="], - "@elizaos/core": ["@elizaos/core@1.0.0-beta.52", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-trace-otlp-http": "^0.53.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/sdk-metrics": "^1.26.0", "@opentelemetry/sdk-node": "^0.53.0", "buffer": "^6.0.3", "crypto-browserify": "^3.12.1", "dotenv": "16.4.5", "events": "^3.3.0", "glob": "11.0.0", "handlebars": "^4.7.8", "js-sha1": "0.7.0", "langchain": "^0.3.15", "pino": "^9.6.0", "pino-pretty": "^13.0.0", "stream-browserify": "^3.0.0", "unique-names-generator": "4.7.1", "uuid": "11.0.3" } }, "sha512-A6YbJiKF3WbcAKQG6e3eC9sG8Dc1vTVUV1PZgJJFLErk2KuetTFSO3bs7OoNgvnTJfILd/8r44ig6kpPYe+FDA=="], + "@elizaos/core": ["@elizaos/core@1.0.0-beta.76", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-trace-otlp-http": "^0.201.1", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/instrumentation-pg": "^0.53.0", "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-metrics": "^2.0.0", "@opentelemetry/sdk-node": "^0.201.1", "@opentelemetry/sdk-trace-node": "^2.0.1", "@opentelemetry/semantic-conventions": "^1.34.0", "buffer": "^6.0.3", "crypto-browserify": "^3.12.1", "dotenv": "16.4.5", "events": "^3.3.0", "glob": "11.0.0", "handlebars": "^4.7.8", "js-sha1": "0.7.0", "langchain": "^0.3.15", "pdfjs-dist": "^5.2.133", "pino": "^9.6.0", "pino-pretty": "^13.0.0", "stream-browserify": "^3.0.0", "unique-names-generator": "4.7.1", "uuid": "11.0.3", "vitest": "^3.1.3", "zod": "^3.24.4" } }, "sha512-4HzsJH1VaaaTCWlKnTuHWZfGIrSaGBuDYFnxUKWQ6pFpWrthO5dzPmzB5QAt/vya3eW76LBnIZn+SamAufchnw=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.4", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q=="], @@ -101,59 +101,89 @@ "@langchain/textsplitters": ["@langchain/textsplitters@0.1.0", "", { "dependencies": { "js-tiktoken": "^1.0.12" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" } }, "sha512-djI4uw9rlkAb5iMhtLED+xJebDdAG935AdP4eRTB02R7OB/act55Bj9wsskhZsvuyQRpO4O1wQOp85s6T6GWmw=="], + "@napi-rs/canvas": ["@napi-rs/canvas@0.1.70", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "0.1.70", "@napi-rs/canvas-darwin-arm64": "0.1.70", "@napi-rs/canvas-darwin-x64": "0.1.70", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.70", "@napi-rs/canvas-linux-arm64-gnu": "0.1.70", "@napi-rs/canvas-linux-arm64-musl": "0.1.70", "@napi-rs/canvas-linux-riscv64-gnu": "0.1.70", "@napi-rs/canvas-linux-x64-gnu": "0.1.70", "@napi-rs/canvas-linux-x64-musl": "0.1.70", "@napi-rs/canvas-win32-x64-msvc": "0.1.70" } }, "sha512-nD6NGa4JbNYSZYsTnLGrqe9Kn/lCkA4ybXt8sx5ojDqZjr2i0TWAHxx/vhgfjX+i3hCdKWufxYwi7CfXqtITSA=="], + + "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@0.1.70", "", { "os": "android", "cpu": "arm64" }, "sha512-I/YOuQ0wbkVYxVaYtCgN42WKTYxNqFA0gTcTrHIGG1jfpDSyZWII/uHcjOo4nzd19io6Y4+/BqP8E5hJgf9OmQ=="], + + "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@0.1.70", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4pPGyXetHIHkw2TOJHujt3mkCP8LdDu8+CT15ld9Id39c752RcI0amDHSuMLMQfAjvusA9B5kKxazwjMGjEJpQ=="], + + "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@0.1.70", "", { "os": "darwin", "cpu": "x64" }, "sha512-+2N6Os9LbkmDMHL+raknrUcLQhsXzc5CSXRbXws9C3pv/mjHRVszQ9dhFUUe9FjfPhCJznO6USVdwOtu7pOrzQ=="], + + "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@0.1.70", "", { "os": "linux", "cpu": "arm" }, "sha512-QjscX9OaKq/990sVhSMj581xuqLgiaPVMjjYvWaCmAJRkNQ004QfoSMEm3FoTqM4DRoquP8jvuEXScVJsc1rqQ=="], + + "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@0.1.70", "", { "os": "linux", "cpu": "arm64" }, "sha512-LNakMOwwqwiHIwMpnMAbFRczQMQ7TkkMyATqFCOtUJNlE6LPP/QiUj/mlFrNbUn/hctqShJ60gWEb52ZTALbVw=="], + + "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@0.1.70", "", { "os": "linux", "cpu": "arm64" }, "sha512-wBTOllEYNfJCHOdZj9v8gLzZ4oY3oyPX8MSRvaxPm/s7RfEXxCyZ8OhJ5xAyicsDdbE5YBZqdmaaeP5+xKxvtg=="], + + "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@0.1.70", "", { "os": "linux", "cpu": "none" }, "sha512-GVUUPC8TuuFqHip0rxHkUqArQnlzmlXmTEBuXAWdgCv85zTCFH8nOHk/YCF5yo0Z2eOm8nOi90aWs0leJ4OE5Q=="], + + "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@0.1.70", "", { "os": "linux", "cpu": "x64" }, "sha512-/kvUa2lZRwGNyfznSn5t1ShWJnr/m5acSlhTV3eXECafObjl0VBuA1HJw0QrilLpb4Fe0VLywkpD1NsMoVDROQ=="], + + "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@0.1.70", "", { "os": "linux", "cpu": "x64" }, "sha512-aqlv8MLpycoMKRmds7JWCfVwNf1fiZxaU7JwJs9/ExjTD8lX2KjsO7CTeAj5Cl4aEuzxUWbJPUUE2Qu9cZ1vfg=="], + + "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@0.1.70", "", { "os": "win32", "cpu": "x64" }, "sha512-Q9QU3WIpwBTVHk4cPfBjGHGU4U0llQYRXgJtFtYqqGNEOKVN4OT6PQ+ve63xwIPODMpZ0HHyj/KLGc9CWc3EtQ=="], + "@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="], - "@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.53.0", "", { "dependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-8HArjKx+RaAI8uEIgcORbZIPklyh1YLjPSBus8hjRmvLi6DeFzgOcdZ7KwPabKj8mXF8dX0hyfAyGfycz0DbFw=="], + "@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.201.1", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-IxcFDP1IGMDemVFG2by/AMK+/o6EuBQ8idUq3xZ6MxgQGeumYZuX5OwR0h9HuvcUc/JPjQGfU5OHKIKYDJcXeA=="], + + "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.0.1", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw=="], + + "@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], + + "@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/exporter-logs-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ACV2Az9BHRcAaPMYBnYMwKHNn2JwkzzsT3cdeG6+Tokm47fFfpf2xk3sq3QvX0Gk+TXW7q6d+OfBuYfWoAud2g=="], + + "@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-flYr1tr/wlUxsVc2ZYt/seNLgp3uagyUg9MtjiHYyaMQcN4XuEuI4UjUFwXAGQjd2khmXeie5YnTmO8gzyzemw=="], - "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@1.26.0", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-HedpXXYzzbaoutw6DFLWLDket2FwLkLpil4hGCZ1xYEIMTcivdfwEOISgdbLEWyG3HW52gTq2V9mOVJrONgiwg=="], + "@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ZVkutDoQYLAkWmpbmd9XKZ9NeBQS6GPxLl/NZ/uDMq+tFnmZu1p0cvZ43x5+TpFoGkjPR6QYHCxkcZBwI9M8ag=="], - "@opentelemetry/core": ["@opentelemetry/core@1.26.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1iKxXXE8415Cdv0yjG3G6hQnB5eVEsJce3QaawX8SjDn0mAS0ZM8fAbZZJD4ajvhC15cePvosSCut404KrIIvQ=="], + "@opentelemetry/exporter-metrics-otlp-grpc": ["@opentelemetry/exporter-metrics-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ywo4TpQNOLi07K7P3CaymzS8XlDGfTFmMQ4oSPsZv38/gAf3/wPVh2uL5qYAFqrVokNCmkcaeCwX3QSy0g9b/A=="], - "@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/exporter-logs-otlp-grpc@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-grpc-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/sdk-logs": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-x5ygAQgWAQOI+UOhyV3z9eW7QU2dCfnfOuIBiyYmC2AWr74f6x/3JBnP27IAcEx6aihpqBYWKnpoUTztkVPAZw=="], + "@opentelemetry/exporter-metrics-otlp-http": ["@opentelemetry/exporter-metrics-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-LMRVg2yTev28L51RLLUK3gY0avMa1RVBq7IkYNtXDBxJRcd0TGGq/0rqfk7Y4UIM9NCJhDIUFHeGg8NpSgSWcw=="], - "@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/sdk-logs": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-cSRKgD/n8rb+Yd+Cif6EnHEL/VZg1o8lEcEwFji1lwene6BdH51Zh3feAD9p2TyVoBKrl6Q9Zm2WltSp2k9gWQ=="], + "@opentelemetry/exporter-metrics-otlp-proto": ["@opentelemetry/exporter-metrics-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-9ie2jcaUQZdIoe6B02r0rF4Gz+JsZ9mev/2pYou1N0woOUkFM8xwO6BAlORnrFVslqF/XO5WG3q5FsTbuC5iiw=="], - "@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-jhEcVL1deeWNmTUP05UZMriZPSWUBcfg94ng7JuBb1q2NExgnADQFl1VQQ+xo62/JepK+MxQe4xAwlsDQFbISA=="], + "@opentelemetry/exporter-prometheus": ["@opentelemetry/exporter-prometheus@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-J6/4KgljApWda/2YBMHHZg6vaZ6H8BjFInO8YQW+N0al1LjGAAq3pFRCEHpU6GI7ZlkphCxKy6MUjXOZVM8KWQ=="], - "@opentelemetry/exporter-trace-otlp-grpc": ["@opentelemetry/exporter-trace-otlp-grpc@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-grpc-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-m6KSh6OBDwfDjpzPVbuJbMgMbkoZfpxYH2r262KckgX9cMYvooWXEKzlJYsNDC6ADr28A1rtRoUVRwNfIN4tUg=="], + "@opentelemetry/exporter-trace-otlp-grpc": ["@opentelemetry/exporter-trace-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0ZM5CBoZbufXckxi/SWwP5B++CjPWS6N1i+K7f+GhRxYWVGt/yh4eiV3jklZKWw/DUyMkUvUOo0GW1RxoiLoZQ=="], - "@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/exporter-trace-otlp-http@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-m7F5ZTq+V9mKGWYpX8EnZ7NjoqAU7VemQ1E2HAG+W/u0wpY1x0OmbxAXfGKFHCspdJk8UKlwPGrpcB8nay3P8A=="], + "@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/exporter-trace-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Nw3pIqATC/9LfSGrMiQeeMQ7/z7W2D0wKPxtXwAcr7P64JW7KSH4YSX7Ji8Ti3MmB79NQg6imdagfegJDB0rng=="], - "@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/exporter-trace-otlp-proto@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-T/bdXslwRKj23S96qbvGtaYOdfyew3TjPEKOk5mHjkCmkVl1O9C/YMdejwSsdLdOq2YW30KjR9kVi0YMxZushQ=="], + "@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/exporter-trace-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-wMxdDDyW+lmmenYGBp0evCoKzajXqIw6SSaZtaF/uqKR9/POhC/9vudnc+kf8W49hYFyIEutPrc1hA0exe3UwQ=="], - "@opentelemetry/exporter-zipkin": ["@opentelemetry/exporter-zipkin@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-PW5R34n3SJHO4t0UetyHKiXL6LixIqWN6lWncg3eRXhKuT30x+b7m5sDJS0kEWRfHeS+kG7uCw2vBzmB2lk3Dw=="], + "@opentelemetry/exporter-zipkin": ["@opentelemetry/exporter-zipkin@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-a9eeyHIipfdxzCfc2XPrE+/TI3wmrZUDFtG2RRXHSbZZULAny7SyybSvaDvS77a7iib5MPiAvluwVvbGTsHxsw=="], - "@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.200.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.200.0", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-pmPlzfJd+vvgaZd/reMsC8RWgTXn2WY1OWT5RT42m3aOn5532TozwXNDhg1vzqJ+jnvmkREcdLr27ebJEQt0Jg=="], + "@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-6EOSoT2zcyBM3VryAzn35ytjRrOMeaWZyzQ/PHVfxoXp5rMf7UUgVToqxOhQffKOHtC7Dma4bHt+DuwIBBZyZA=="], - "@opentelemetry/instrumentation-pg": ["@opentelemetry/instrumentation-pg@0.52.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.200.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0", "@types/pg": "8.6.1", "@types/pg-pool": "2.0.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-OBpqlxTqmFkZGHaHV4Pzd95HkyKVS+vf0N5wVX3BSb8uqsvOrW62I1qt+2jNsZ13dtG5eOzvcsQTMGND76wizA=="], + "@opentelemetry/instrumentation-pg": ["@opentelemetry/instrumentation-pg@0.53.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0", "@types/pg": "8.6.1", "@types/pg-pool": "2.0.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-riWbJvSviTAsjeuq8fn7Y7+CXEYf3sGR18WfLeM7GgSnptTOur1++SLTN7XogqiwP3LFFQ0GLoYe+hxVOEyEpw=="], - "@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.53.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-transformer": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-UCWPreGQEhD6FjBaeDuXhiMf6kkBODF0ZQzrk/tuQcaVDJ+dDQ/xhJp192H9yWnKxVpEjFrSSLnpqmX4VwX+eA=="], + "@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-FiS/mIWmZXyRxYGyXPHY+I/4+XrYVTD7Fz/zwOHkVPQsA1JTakAOP9fAi6trXMio0dIpzvQujLNiBqGM7ExrQw=="], - "@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/otlp-grpc-exporter-base@0.53.0", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "1.26.0", "@opentelemetry/otlp-exporter-base": "0.53.0", "@opentelemetry/otlp-transformer": "0.53.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-F7RCN8VN+lzSa4fGjewit8Z5fEUpY/lmMVy5EWn2ZpbAabg3EE3sCLuTNfOiooNGnmvzimUPruoeqeko/5/TzQ=="], + "@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/otlp-grpc-exporter-base@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Y0h9hiMvNtUuXUMkYNAt81hxnFuOHHSeu/RC+pXcHe7S6ac0ROlcjdabBKmYSadJxRrP4YfLahLRuNkVtZow4w=="], - "@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-metrics": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-rM0sDA9HD8dluwuBxLetUmoqGJKSAbWenwD65KY9iZhUxdBHRLrIdrABfNDP7aiTjcgK8XFyTn5fhDz7N+W6DA=="], + "@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+q/8Yuhtu9QxCcjEAXEO8fXLjlSnrnVwfzi9jiWaMAppQp69MoagHHomQj02V2WnGjvBod5ajgkbK4IoWab50A=="], - "@opentelemetry/propagator-b3": ["@opentelemetry/propagator-b3@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-vvVkQLQ/lGGyEy9GT8uFnI047pajSOVnZI2poJqVGD3nJ+B9sFGdlHNnQKophE3lHfnIH0pw2ubrCTjZCgIj+Q=="], + "@opentelemetry/propagator-b3": ["@opentelemetry/propagator-b3@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Hc09CaQ8Tf5AGLmf449H726uRoBNGPBL4bjr7AnnUpzWMvhdn61F78z9qb6IqB737TffBsokGAK1XykFEZ1igw=="], - "@opentelemetry/propagator-jaeger": ["@opentelemetry/propagator-jaeger@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-DelFGkCdaxA1C/QA0Xilszfr0t4YbGd3DjxiCDPh34lfnFr+VkkrjV9S8ZTJvAzfdKERXhfOxIKBoGPJwoSz7Q=="], + "@opentelemetry/propagator-jaeger": ["@opentelemetry/propagator-jaeger@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-7PMdPBmGVH2eQNb/AtSJizQNgeNTfh6jQFqys6lfhd6P4r+m/nTh3gKPPpaCXVdRQ+z93vfKk+4UGty390283w=="], - "@opentelemetry/resources": ["@opentelemetry/resources@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-CPNYchBE7MBecCSVy0HKpUISEeJOniWqcHaAHpmasZ3j9o6V3AyBzhRc90jdmemq0HOxDr6ylhUbDhBqqPpeNw=="], + "@opentelemetry/resources": ["@opentelemetry/resources@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="], - "@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-dhSisnEgIj/vJZXZV6f6KcTnyLDx/VuQ6l3ejuZpMpPlh9S1qMHiZU9NMmOkVkwwHkMy3G6mEBwdP23vUZVr4g=="], + "@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-Ug8gtpssUNUnfpotB9ZhnSsPSGDu+7LngTMgKl31mmVJwLAKyl6jC8diZrMcGkSgBh0o5dbg9puvLyR25buZfw=="], - "@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.30.1", "", { "dependencies": { "@opentelemetry/core": "1.30.1", "@opentelemetry/resources": "1.30.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog=="], + "@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="], - "@opentelemetry/sdk-node": ["@opentelemetry/sdk-node@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/exporter-logs-otlp-grpc": "0.53.0", "@opentelemetry/exporter-logs-otlp-http": "0.53.0", "@opentelemetry/exporter-logs-otlp-proto": "0.53.0", "@opentelemetry/exporter-trace-otlp-grpc": "0.53.0", "@opentelemetry/exporter-trace-otlp-http": "0.53.0", "@opentelemetry/exporter-trace-otlp-proto": "0.53.0", "@opentelemetry/exporter-zipkin": "1.26.0", "@opentelemetry/instrumentation": "0.53.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/sdk-logs": "0.53.0", "@opentelemetry/sdk-metrics": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "@opentelemetry/sdk-trace-node": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0hsxfq3BKy05xGktwG8YdGdxV978++x40EAKyKr1CaHZRh8uqVlXnclnl7OMi9xLMJEcXUw7lGhiRlArFcovyg=="], + "@opentelemetry/sdk-node": ["@opentelemetry/sdk-node@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-logs-otlp-grpc": "0.201.1", "@opentelemetry/exporter-logs-otlp-http": "0.201.1", "@opentelemetry/exporter-logs-otlp-proto": "0.201.1", "@opentelemetry/exporter-metrics-otlp-grpc": "0.201.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/exporter-metrics-otlp-proto": "0.201.1", "@opentelemetry/exporter-prometheus": "0.201.1", "@opentelemetry/exporter-trace-otlp-grpc": "0.201.1", "@opentelemetry/exporter-trace-otlp-http": "0.201.1", "@opentelemetry/exporter-trace-otlp-proto": "0.201.1", "@opentelemetry/exporter-zipkin": "2.0.1", "@opentelemetry/instrumentation": "0.201.1", "@opentelemetry/propagator-b3": "2.0.1", "@opentelemetry/propagator-jaeger": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/sdk-trace-node": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-OdkYe6ZEFbPq+YXhebuiYpPECIBrrKgFJoAQVATllKlB5RDQDTE4J84/8LwGfQqSxBiSK2u1aSaFpzgBVoBrKA=="], - "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0", "@opentelemetry/semantic-conventions": "1.27.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-olWQldtvbK4v22ymrKLbIcBi9L2SpMO84sCPY54IVsJhP9fRsxJT194C/AVaAuJzLE30EdhhM1VmvVYR7az+cw=="], + "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="], - "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@1.26.0", "", { "dependencies": { "@opentelemetry/context-async-hooks": "1.26.0", "@opentelemetry/core": "1.26.0", "@opentelemetry/propagator-b3": "1.26.0", "@opentelemetry/propagator-jaeger": "1.26.0", "@opentelemetry/sdk-trace-base": "1.26.0", "semver": "^7.5.2" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Fj5IVKrj0yeUwlewCRwzOVcr5avTuNnMHWf7GPc1t6WaT78J6CJyF3saZ/0RkZfdeNO8IcBl/bNcWMVZBMRW8Q=="], + "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.0.1", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.0.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA=="], - "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.28.0", "", {}, "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA=="], + "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.34.0", "", {}, "sha512-aKcOkyrorBGlajjRdVoJWHTxfxO1vCNHLJVlSDaRHDIdjU+pX8IYQPvPDkYiujKLbRnWU+1TBwEt0QRgSm4SGA=="], "@opentelemetry/sql-common": ["@opentelemetry/sql-common@0.41.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" } }, "sha512-pmzXctVbEERbqSfiAgdes9Y63xjoOyXcD7B6IXBkVb+vbM7M9U98mn33nGXxPf4dfYR0M+vhcKRZmbSJ7HfqFA=="], @@ -627,6 +657,8 @@ "pbkdf2": ["pbkdf2@3.1.2", "", { "dependencies": { "create-hash": "^1.1.2", "create-hmac": "^1.1.4", "ripemd160": "^2.0.1", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA=="], + "pdfjs-dist": ["pdfjs-dist@5.2.133", "", { "optionalDependencies": { "@napi-rs/canvas": "^0.1.67" } }, "sha512-abE6ZWDxztt+gGFzfm4bX2ggfxUk9wsDEoFzIJm9LozaY3JdXR7jyLK4Bjs+XLXplCduuWS1wGhPC4tgTn/kzg=="], + "pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="], "pg-protocol": ["pg-protocol@1.10.0", "", {}, "sha512-IpdytjudNuLv8nhlHs/UrVBhU0e78J0oIS/0AVdTbWxSOkFUVdsHC/NrorO6nXsQNDTT1kzDSOMJubBQviX18Q=="], @@ -853,31 +885,7 @@ "@langchain/core/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], - "@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], - - "@opentelemetry/exporter-zipkin/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], - - "@opentelemetry/instrumentation/@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.200.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-IKJBQxh91qJ+3ssRly5hYEJ8NDHu9oY/B1PXVSCWf7zytmYO9RNLB0Ox9XQ/fJ8m6gY6Q6NtBWlmXfaXt5Uc4Q=="], - - "@opentelemetry/instrumentation-pg/@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], - - "@opentelemetry/otlp-transformer/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0SvDXmou/JjzSDOjUmetAAvcKQW6ZrvosU0rkbDGpXvvZN+pQF6JbK/Kd4hNdK4q/22yeruqvukXEJyySTzyTQ=="], - - "@opentelemetry/resources/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], - - "@opentelemetry/sdk-metrics/@opentelemetry/core": ["@opentelemetry/core@1.30.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "1.28.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ=="], - - "@opentelemetry/sdk-metrics/@opentelemetry/resources": ["@opentelemetry/resources@1.30.1", "", { "dependencies": { "@opentelemetry/core": "1.30.1", "@opentelemetry/semantic-conventions": "1.28.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA=="], - - "@opentelemetry/sdk-node/@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.53.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.53.0", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "semver": "^7.5.2", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-DMwg0hy4wzf7K73JJtl95m/e0boSoWhH07rfvHvYzQtBD3Bmv0Wc1x733vyZBqmFm8OjJD0/pfiUg1W3JjFX0A=="], - - "@opentelemetry/sdk-node/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@1.26.0", "", { "dependencies": { "@opentelemetry/core": "1.26.0", "@opentelemetry/resources": "1.26.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-0SvDXmou/JjzSDOjUmetAAvcKQW6ZrvosU0rkbDGpXvvZN+pQF6JbK/Kd4hNdK4q/22yeruqvukXEJyySTzyTQ=="], - - "@opentelemetry/sdk-node/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], - - "@opentelemetry/sdk-trace-base/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.27.0", "", {}, "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg=="], - - "@opentelemetry/sql-common/@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], + "@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], "@scure/bip32/@noble/curves": ["@noble/curves@1.8.2", "", { "dependencies": { "@noble/hashes": "1.7.2" } }, "sha512-vnI7V6lFNe0tLAuJMu+2sX+FcL14TaCWy1qiczg1VwRmPrpQCdq5ESXQMqUc2tluRNf6irBXrWbl1mGN8uaU/g=="], @@ -959,10 +967,6 @@ "yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - "@opentelemetry/instrumentation-pg/@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], - - "@opentelemetry/sql-common/@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], - "browserify-sign/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], "browserify-sign/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], diff --git a/package.json b/package.json index ad8004f..67d16b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.56", + "version": "1.0.0-beta.57", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From 15f1a7ef9752d26fc4edc5e76d6a74a89760cf6c Mon Sep 17 00:00:00 2001 From: 0xbbjoker <0xbbjoker@proton.me> Date: Tue, 27 May 2025 22:17:07 +0200 Subject: [PATCH 27/39] chore bump pckg version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 67d16b5..28ae530 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.57", + "version": "1.0.0-beta.58", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From 49f1bca30cd330f2fb39af09304de4395e08ce9b Mon Sep 17 00:00:00 2001 From: 0xbbjoker <0xbbjoker@proton.me> Date: Tue, 27 May 2025 22:19:12 +0200 Subject: [PATCH 28/39] chore: bump version one more time --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 28ae530..4ab1bae 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.58", + "version": "1.0.0-beta.76", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", From 98e55f36619a820d44babc8a1ba8842f6f501cba Mon Sep 17 00:00:00 2001 From: cjft Date: Wed, 28 May 2025 22:05:16 -0600 Subject: [PATCH 29/39] chore: update repository URL and bump version in package.json --- package.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 4ab1bae..2bd1b43 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.76", + "version": "1.0.0-beta.77", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", @@ -42,5 +42,9 @@ "type": "string" } } + }, + "repository": { + "type": "git", + "url": "https://github.com/elizaos-plugins/plugin-tee.git" } } From a2754b9a6fb86f3eed2c0805714ff39b96afdaf1 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Thu, 29 May 2025 19:51:59 -0600 Subject: [PATCH 30/39] update baseUrl, bump version --- package.json | 2 +- tsconfig.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 2bd1b43..9ad1e35 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.77", + "version": "1.0.0-beta.78", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", diff --git a/tsconfig.json b/tsconfig.json index 3c3c58b..de3ee55 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "outDir": "dist", "rootDir": "src", - "baseUrl": "../..", + "baseUrl": ".", "lib": ["ESNext", "DOM"], "target": "ESNext", "module": "Preserve", From 809a090d69964dfc1c88a991e780a006fa09eaa6 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Thu, 29 May 2025 19:58:40 -0600 Subject: [PATCH 31/39] add files, change npmignore, .79 --- .npmignore | 5 +++-- package.json | 9 +++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.npmignore b/.npmignore index 078562e..9f74001 100644 --- a/.npmignore +++ b/.npmignore @@ -2,5 +2,6 @@ !dist/** !package.json -!readme.md -!tsup.config.ts \ No newline at end of file +!README.md +!tsup.config.ts +!LICENSE \ No newline at end of file diff --git a/package.json b/package.json index 9ad1e35..3286a8e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.78", + "version": "1.0.0-beta.79", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", @@ -46,5 +46,10 @@ "repository": { "type": "git", "url": "https://github.com/elizaos-plugins/plugin-tee.git" - } + }, + "files": [ + "dist", + "README.md", + "LICENSE" + ] } From f166ccc2c14b2074355e23b2944745af0d947ff5 Mon Sep 17 00:00:00 2001 From: Christopher Trimboli Date: Thu, 29 May 2025 20:05:21 -0600 Subject: [PATCH 32/39] paths: {} in tsconfig.build --- package.json | 2 +- tsconfig.build.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3286a8e..5c494fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.79", + "version": "1.0.0-beta.80", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", diff --git a/tsconfig.build.json b/tsconfig.build.json index 625391d..b9bb614 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -6,7 +6,8 @@ "sourceMap": true, "inlineSources": true, "declaration": true, - "emitDeclarationOnly": true + "emitDeclarationOnly": true, + "paths": {} }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"] From c0dececd33f4575443a7335db6647f095a1ee487 Mon Sep 17 00:00:00 2001 From: cjft Date: Fri, 30 May 2025 06:22:34 -0600 Subject: [PATCH 33/39] chore: update repository URL and bump version in package.json --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 5c494fc..1a06923 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.80", + "version": "1.0.0-beta.81", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", @@ -45,7 +45,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/elizaos-plugins/plugin-tee.git" + "url": "git+https://github.com/elizaos-plugins/plugin-tee.git" }, "files": [ "dist", From e3a0dd2a7084101b913e98e9a1242dca19352395 Mon Sep 17 00:00:00 2001 From: cjft Date: Fri, 30 May 2025 17:12:06 -0600 Subject: [PATCH 34/39] chore: update npm deployment workflow --- .github/workflows/npm-deploy.yml | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/.github/workflows/npm-deploy.yml b/.github/workflows/npm-deploy.yml index 566a06d..9683956 100644 --- a/.github/workflows/npm-deploy.yml +++ b/.github/workflows/npm-deploy.yml @@ -4,7 +4,6 @@ on: push: branches: - 1.x - - 0.x workflow_dispatch: jobs: @@ -84,22 +83,13 @@ jobs: uses: oven-sh/setup-bun@v2 - name: Install dependencies - run: bun install --frozen-lockfile + run: bun install - name: Build package run: bun run build - name: Publish to npm - run: | - # strip “refs/heads/” prefix - BRANCH=${GITHUB_REF#refs/heads/} - if [[ "$BRANCH" == "1.x" ]]; then - echo "Publishing to npm under the 'beta' tag" - bun publish --tag beta - else - echo "Publishing to npm under the 'latest' tag" - bun publish - fi + run: bun publish env: NPM_CONFIG_TOKEN: ${{ secrets.NPM_TOKEN }} From 674e319e44acd1e210ef32b895bf09a575a97ad0 Mon Sep 17 00:00:00 2001 From: cjft Date: Fri, 30 May 2025 17:12:07 -0600 Subject: [PATCH 35/39] chore: remove bun.lock to regenerate with updated dependencies --- bun.lock | 1006 ------------------------------------------------------ 1 file changed, 1006 deletions(-) delete mode 100644 bun.lock diff --git a/bun.lock b/bun.lock deleted file mode 100644 index 5f960b2..0000000 --- a/bun.lock +++ /dev/null @@ -1,1006 +0,0 @@ -{ - "lockfileVersion": 1, - "workspaces": { - "": { - "name": "@elizaos/plugin-tee", - "dependencies": { - "@elizaos/core": "^1.0.0-beta.76", - "@phala/dstack-sdk": "0.1.11", - "@solana/web3.js": "1.98.2", - "viem": "2.29.4", - }, - "devDependencies": { - "@types/node": "^22.15.3", - "prettier": "3.5.3", - "tsup": "8.5.0", - "typescript": "5.8.3", - "vitest": "^3.1.3", - }, - }, - }, - "packages": { - "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], - - "@babel/runtime": ["@babel/runtime@7.27.1", "", {}, "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog=="], - - "@cfworker/json-schema": ["@cfworker/json-schema@4.1.1", "", {}, "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og=="], - - "@elizaos/core": ["@elizaos/core@1.0.0-beta.76", "", { "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-trace-otlp-http": "^0.201.1", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/instrumentation-pg": "^0.53.0", "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-metrics": "^2.0.0", "@opentelemetry/sdk-node": "^0.201.1", "@opentelemetry/sdk-trace-node": "^2.0.1", "@opentelemetry/semantic-conventions": "^1.34.0", "buffer": "^6.0.3", "crypto-browserify": "^3.12.1", "dotenv": "16.4.5", "events": "^3.3.0", "glob": "11.0.0", "handlebars": "^4.7.8", "js-sha1": "0.7.0", "langchain": "^0.3.15", "pdfjs-dist": "^5.2.133", "pino": "^9.6.0", "pino-pretty": "^13.0.0", "stream-browserify": "^3.0.0", "unique-names-generator": "4.7.1", "uuid": "11.0.3", "vitest": "^3.1.3", "zod": "^3.24.4" } }, "sha512-4HzsJH1VaaaTCWlKnTuHWZfGIrSaGBuDYFnxUKWQ6pFpWrthO5dzPmzB5QAt/vya3eW76LBnIZn+SamAufchnw=="], - - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.4", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q=="], - - "@esbuild/android-arm": ["@esbuild/android-arm@0.25.4", "", { "os": "android", "cpu": "arm" }, "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ=="], - - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.4", "", { "os": "android", "cpu": "arm64" }, "sha512-bBy69pgfhMGtCnwpC/x5QhfxAz/cBgQ9enbtwjf6V9lnPI/hMyT9iWpR1arm0l3kttTr4L0KSLpKmLp/ilKS9A=="], - - "@esbuild/android-x64": ["@esbuild/android-x64@0.25.4", "", { "os": "android", "cpu": "x64" }, "sha512-TVhdVtQIFuVpIIR282btcGC2oGQoSfZfmBdTip2anCaVYcqWlZXGcdcKIUklfX2wj0JklNYgz39OBqh2cqXvcQ=="], - - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Y1giCfM4nlHDWEfSckMzeWNdQS31BQGs9/rouw6Ub91tkK79aIMTH3q9xHvzH8d0wDru5Ci0kWB8b3up/nl16g=="], - - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-CJsry8ZGM5VFVeyUYB3cdKpd/H69PYez4eJh1W/t38vzutdjEjtP7hB6eLKBoOdxcAlCtEYHzQ/PJ/oU9I4u0A=="], - - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.4", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-yYq+39NlTRzU2XmoPW4l5Ifpl9fqSk0nAJYM/V/WUGPEFfek1epLHJIkTQM6bBs1swApjO5nWgvr843g6TjxuQ=="], - - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-0FgvOJ6UUMflsHSPLzdfDnnBBVoCDtBTVyn/MrWloUNvq/5SFmh13l3dvgRPkDihRxb77Y17MbqbCAa2strMQQ=="], - - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.4", "", { "os": "linux", "cpu": "arm" }, "sha512-kro4c0P85GMfFYqW4TWOpvmF8rFShbWGnrLqlzp4X1TNWjRY3JMYUfDCtOxPKOIY8B0WC8HN51hGP4I4hz4AaQ=="], - - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-+89UsQTfXdmjIvZS6nUnOOLoXnkUTB9hR5QAeLrQdzOSWZvNSAXAtcRDHWtqAUtAmv7ZM1WPOOeSxDzzzMogiQ=="], - - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.4", "", { "os": "linux", "cpu": "ia32" }, "sha512-yTEjoapy8UP3rv8dB0ip3AfMpRbyhSN3+hY8mo/i4QXFeDxmiYbEKp3ZRjBKcOP862Ua4b1PDfwlvbuwY7hIGQ=="], - - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-NeqqYkrcGzFwi6CGRGNMOjWGGSYOpqwCjS9fvaUlX5s3zwOtn1qwg1s2iE2svBe4Q/YOG1q6875lcAoQK/F4VA=="], - - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-IcvTlF9dtLrfL/M8WgNI/qJYBENP3ekgsHbYUIzEzq5XJzzVEV/fXY9WFPfEEXmu3ck2qJP8LG/p3Q8f7Zc2Xg=="], - - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-HOy0aLTJTVtoTeGZh4HSXaO6M95qu4k5lJcH4gxv56iaycfz1S8GO/5Jh6X4Y1YiI0h7cRyLi+HixMR+88swag=="], - - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.4", "", { "os": "linux", "cpu": "none" }, "sha512-i8JUDAufpz9jOzo4yIShCTcXzS07vEgWzyX3NH2G7LEFVgrLEhjwL3ajFE4fZI3I4ZgiM7JH3GQ7ReObROvSUA=="], - - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-jFnu+6UbLlzIjPQpWCNh5QtrcNfMLjgIavnwPQAfoGx4q17ocOU9MsQ2QVvFxwQoWpZT8DvTLooTvmOQXkO51g=="], - - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA=="], - - "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.4", "", { "os": "none", "cpu": "arm64" }, "sha512-vUnkBYxZW4hL/ie91hSqaSNjulOnYXE1VSLusnvHg2u3jewJBz3YzB9+oCw8DABeVqZGg94t9tyZFoHma8gWZQ=="], - - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.4", "", { "os": "none", "cpu": "x64" }, "sha512-XAg8pIQn5CzhOB8odIcAm42QsOfa98SBeKUdo4xa8OvX8LbMZqEtgeWE9P/Wxt7MlG2QqvjGths+nq48TrUiKw=="], - - "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.4", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-Ct2WcFEANlFDtp1nVAXSNBPDxyU+j7+tId//iHXU2f/lN5AmO4zLyhDcpR5Cz1r08mVxzt3Jpyt4PmXQ1O6+7A=="], - - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.4", "", { "os": "openbsd", "cpu": "x64" }, "sha512-xAGGhyOQ9Otm1Xu8NT1ifGLnA6M3sJxZ6ixylb+vIUVzvvd6GOALpwQrYrtlPouMqd/vSbgehz6HaVk4+7Afhw=="], - - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.4", "", { "os": "sunos", "cpu": "x64" }, "sha512-Mw+tzy4pp6wZEK0+Lwr76pWLjrtjmJyUB23tHKqEDP74R3q95luY/bXqXZeYl4NYlvwOqoRKlInQialgCKy67Q=="], - - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-AVUP428VQTSddguz9dO9ngb+E5aScyg7nOeJDrF1HPYu555gmza3bDGMPhmVXL8svDSoqPCsCPjb265yG/kLKQ=="], - - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-i1sW+1i+oWvQzSgfRcxxG2k4I9n3O9NRqy8U+uugaT2Dy7kLO9Y7wI72haOahxceMX8hZAzgGou1FhndRldxRg=="], - - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.4", "", { "os": "win32", "cpu": "x64" }, "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ=="], - - "@grpc/grpc-js": ["@grpc/grpc-js@1.13.3", "", { "dependencies": { "@grpc/proto-loader": "^0.7.13", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-FTXHdOoPbZrBjlVLHuKbDZnsTxXv2BlHF57xw6LuThXacXvtkahEPED0CKMk6obZDf65Hv4k3z62eyPNpvinIg=="], - - "@grpc/proto-loader": ["@grpc/proto-loader@0.7.15", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="], - - "@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], - - "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.8", "", { "dependencies": { "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA=="], - - "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], - - "@jridgewell/set-array": ["@jridgewell/set-array@1.2.1", "", {}, "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.0", "", {}, "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="], - - "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], - - "@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="], - - "@langchain/core": ["@langchain/core@0.3.56", "", { "dependencies": { "@cfworker/json-schema": "^4.0.2", "ansi-styles": "^5.0.0", "camelcase": "6", "decamelize": "1.2.0", "js-tiktoken": "^1.0.12", "langsmith": "^0.3.29", "mustache": "^4.2.0", "p-queue": "^6.6.2", "p-retry": "4", "uuid": "^10.0.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" } }, "sha512-eF9MyInM9RLNisAygiCrzHnqzOnuzGWy4f1SAqAis+XIMhcA98WuZDNWxyX9pP3aKQGc47FAJ/9XWJwv5KiquA=="], - - "@langchain/openai": ["@langchain/openai@0.5.10", "", { "dependencies": { "js-tiktoken": "^1.0.12", "openai": "^4.96.0", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" }, "peerDependencies": { "@langchain/core": ">=0.3.48 <0.4.0" } }, "sha512-hBQIWjcVxGS7tgVvgBBmrZ5jSaJ8nu9g6V64/Tx6KGjkW7VdGmUvqCO+koiQCOZVL7PBJkHWAvDsbghPYXiZEA=="], - - "@langchain/textsplitters": ["@langchain/textsplitters@0.1.0", "", { "dependencies": { "js-tiktoken": "^1.0.12" }, "peerDependencies": { "@langchain/core": ">=0.2.21 <0.4.0" } }, "sha512-djI4uw9rlkAb5iMhtLED+xJebDdAG935AdP4eRTB02R7OB/act55Bj9wsskhZsvuyQRpO4O1wQOp85s6T6GWmw=="], - - "@napi-rs/canvas": ["@napi-rs/canvas@0.1.70", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "0.1.70", "@napi-rs/canvas-darwin-arm64": "0.1.70", "@napi-rs/canvas-darwin-x64": "0.1.70", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.70", "@napi-rs/canvas-linux-arm64-gnu": "0.1.70", "@napi-rs/canvas-linux-arm64-musl": "0.1.70", "@napi-rs/canvas-linux-riscv64-gnu": "0.1.70", "@napi-rs/canvas-linux-x64-gnu": "0.1.70", "@napi-rs/canvas-linux-x64-musl": "0.1.70", "@napi-rs/canvas-win32-x64-msvc": "0.1.70" } }, "sha512-nD6NGa4JbNYSZYsTnLGrqe9Kn/lCkA4ybXt8sx5ojDqZjr2i0TWAHxx/vhgfjX+i3hCdKWufxYwi7CfXqtITSA=="], - - "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@0.1.70", "", { "os": "android", "cpu": "arm64" }, "sha512-I/YOuQ0wbkVYxVaYtCgN42WKTYxNqFA0gTcTrHIGG1jfpDSyZWII/uHcjOo4nzd19io6Y4+/BqP8E5hJgf9OmQ=="], - - "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@0.1.70", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4pPGyXetHIHkw2TOJHujt3mkCP8LdDu8+CT15ld9Id39c752RcI0amDHSuMLMQfAjvusA9B5kKxazwjMGjEJpQ=="], - - "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@0.1.70", "", { "os": "darwin", "cpu": "x64" }, "sha512-+2N6Os9LbkmDMHL+raknrUcLQhsXzc5CSXRbXws9C3pv/mjHRVszQ9dhFUUe9FjfPhCJznO6USVdwOtu7pOrzQ=="], - - "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@0.1.70", "", { "os": "linux", "cpu": "arm" }, "sha512-QjscX9OaKq/990sVhSMj581xuqLgiaPVMjjYvWaCmAJRkNQ004QfoSMEm3FoTqM4DRoquP8jvuEXScVJsc1rqQ=="], - - "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@0.1.70", "", { "os": "linux", "cpu": "arm64" }, "sha512-LNakMOwwqwiHIwMpnMAbFRczQMQ7TkkMyATqFCOtUJNlE6LPP/QiUj/mlFrNbUn/hctqShJ60gWEb52ZTALbVw=="], - - "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@0.1.70", "", { "os": "linux", "cpu": "arm64" }, "sha512-wBTOllEYNfJCHOdZj9v8gLzZ4oY3oyPX8MSRvaxPm/s7RfEXxCyZ8OhJ5xAyicsDdbE5YBZqdmaaeP5+xKxvtg=="], - - "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@0.1.70", "", { "os": "linux", "cpu": "none" }, "sha512-GVUUPC8TuuFqHip0rxHkUqArQnlzmlXmTEBuXAWdgCv85zTCFH8nOHk/YCF5yo0Z2eOm8nOi90aWs0leJ4OE5Q=="], - - "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@0.1.70", "", { "os": "linux", "cpu": "x64" }, "sha512-/kvUa2lZRwGNyfznSn5t1ShWJnr/m5acSlhTV3eXECafObjl0VBuA1HJw0QrilLpb4Fe0VLywkpD1NsMoVDROQ=="], - - "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@0.1.70", "", { "os": "linux", "cpu": "x64" }, "sha512-aqlv8MLpycoMKRmds7JWCfVwNf1fiZxaU7JwJs9/ExjTD8lX2KjsO7CTeAj5Cl4aEuzxUWbJPUUE2Qu9cZ1vfg=="], - - "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@0.1.70", "", { "os": "win32", "cpu": "x64" }, "sha512-Q9QU3WIpwBTVHk4cPfBjGHGU4U0llQYRXgJtFtYqqGNEOKVN4OT6PQ+ve63xwIPODMpZ0HHyj/KLGc9CWc3EtQ=="], - - "@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], - - "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - - "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="], - - "@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.201.1", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-IxcFDP1IGMDemVFG2by/AMK+/o6EuBQ8idUq3xZ6MxgQGeumYZuX5OwR0h9HuvcUc/JPjQGfU5OHKIKYDJcXeA=="], - - "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.0.1", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw=="], - - "@opentelemetry/core": ["@opentelemetry/core@2.0.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="], - - "@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/exporter-logs-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ACV2Az9BHRcAaPMYBnYMwKHNn2JwkzzsT3cdeG6+Tokm47fFfpf2xk3sq3QvX0Gk+TXW7q6d+OfBuYfWoAud2g=="], - - "@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-flYr1tr/wlUxsVc2ZYt/seNLgp3uagyUg9MtjiHYyaMQcN4XuEuI4UjUFwXAGQjd2khmXeie5YnTmO8gzyzemw=="], - - "@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ZVkutDoQYLAkWmpbmd9XKZ9NeBQS6GPxLl/NZ/uDMq+tFnmZu1p0cvZ43x5+TpFoGkjPR6QYHCxkcZBwI9M8ag=="], - - "@opentelemetry/exporter-metrics-otlp-grpc": ["@opentelemetry/exporter-metrics-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ywo4TpQNOLi07K7P3CaymzS8XlDGfTFmMQ4oSPsZv38/gAf3/wPVh2uL5qYAFqrVokNCmkcaeCwX3QSy0g9b/A=="], - - "@opentelemetry/exporter-metrics-otlp-http": ["@opentelemetry/exporter-metrics-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-LMRVg2yTev28L51RLLUK3gY0avMa1RVBq7IkYNtXDBxJRcd0TGGq/0rqfk7Y4UIM9NCJhDIUFHeGg8NpSgSWcw=="], - - "@opentelemetry/exporter-metrics-otlp-proto": ["@opentelemetry/exporter-metrics-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-9ie2jcaUQZdIoe6B02r0rF4Gz+JsZ9mev/2pYou1N0woOUkFM8xwO6BAlORnrFVslqF/XO5WG3q5FsTbuC5iiw=="], - - "@opentelemetry/exporter-prometheus": ["@opentelemetry/exporter-prometheus@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-J6/4KgljApWda/2YBMHHZg6vaZ6H8BjFInO8YQW+N0al1LjGAAq3pFRCEHpU6GI7ZlkphCxKy6MUjXOZVM8KWQ=="], - - "@opentelemetry/exporter-trace-otlp-grpc": ["@opentelemetry/exporter-trace-otlp-grpc@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0ZM5CBoZbufXckxi/SWwP5B++CjPWS6N1i+K7f+GhRxYWVGt/yh4eiV3jklZKWw/DUyMkUvUOo0GW1RxoiLoZQ=="], - - "@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/exporter-trace-otlp-http@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Nw3pIqATC/9LfSGrMiQeeMQ7/z7W2D0wKPxtXwAcr7P64JW7KSH4YSX7Ji8Ti3MmB79NQg6imdagfegJDB0rng=="], - - "@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/exporter-trace-otlp-proto@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-wMxdDDyW+lmmenYGBp0evCoKzajXqIw6SSaZtaF/uqKR9/POhC/9vudnc+kf8W49hYFyIEutPrc1hA0exe3UwQ=="], - - "@opentelemetry/exporter-zipkin": ["@opentelemetry/exporter-zipkin@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-a9eeyHIipfdxzCfc2XPrE+/TI3wmrZUDFtG2RRXHSbZZULAny7SyybSvaDvS77a7iib5MPiAvluwVvbGTsHxsw=="], - - "@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-6EOSoT2zcyBM3VryAzn35ytjRrOMeaWZyzQ/PHVfxoXp5rMf7UUgVToqxOhQffKOHtC7Dma4bHt+DuwIBBZyZA=="], - - "@opentelemetry/instrumentation-pg": ["@opentelemetry/instrumentation-pg@0.53.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0", "@types/pg": "8.6.1", "@types/pg-pool": "2.0.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-riWbJvSviTAsjeuq8fn7Y7+CXEYf3sGR18WfLeM7GgSnptTOur1++SLTN7XogqiwP3LFFQ0GLoYe+hxVOEyEpw=="], - - "@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.201.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-FiS/mIWmZXyRxYGyXPHY+I/4+XrYVTD7Fz/zwOHkVPQsA1JTakAOP9fAi6trXMio0dIpzvQujLNiBqGM7ExrQw=="], - - "@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/otlp-grpc-exporter-base@0.201.1", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Y0h9hiMvNtUuXUMkYNAt81hxnFuOHHSeu/RC+pXcHe7S6ac0ROlcjdabBKmYSadJxRrP4YfLahLRuNkVtZow4w=="], - - "@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+q/8Yuhtu9QxCcjEAXEO8fXLjlSnrnVwfzi9jiWaMAppQp69MoagHHomQj02V2WnGjvBod5ajgkbK4IoWab50A=="], - - "@opentelemetry/propagator-b3": ["@opentelemetry/propagator-b3@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Hc09CaQ8Tf5AGLmf449H726uRoBNGPBL4bjr7AnnUpzWMvhdn61F78z9qb6IqB737TffBsokGAK1XykFEZ1igw=="], - - "@opentelemetry/propagator-jaeger": ["@opentelemetry/propagator-jaeger@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-7PMdPBmGVH2eQNb/AtSJizQNgeNTfh6jQFqys6lfhd6P4r+m/nTh3gKPPpaCXVdRQ+z93vfKk+4UGty390283w=="], - - "@opentelemetry/resources": ["@opentelemetry/resources@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="], - - "@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-Ug8gtpssUNUnfpotB9ZhnSsPSGDu+7LngTMgKl31mmVJwLAKyl6jC8diZrMcGkSgBh0o5dbg9puvLyR25buZfw=="], - - "@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="], - - "@opentelemetry/sdk-node": ["@opentelemetry/sdk-node@0.201.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-logs-otlp-grpc": "0.201.1", "@opentelemetry/exporter-logs-otlp-http": "0.201.1", "@opentelemetry/exporter-logs-otlp-proto": "0.201.1", "@opentelemetry/exporter-metrics-otlp-grpc": "0.201.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/exporter-metrics-otlp-proto": "0.201.1", "@opentelemetry/exporter-prometheus": "0.201.1", "@opentelemetry/exporter-trace-otlp-grpc": "0.201.1", "@opentelemetry/exporter-trace-otlp-http": "0.201.1", "@opentelemetry/exporter-trace-otlp-proto": "0.201.1", "@opentelemetry/exporter-zipkin": "2.0.1", "@opentelemetry/instrumentation": "0.201.1", "@opentelemetry/propagator-b3": "2.0.1", "@opentelemetry/propagator-jaeger": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/sdk-trace-node": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-OdkYe6ZEFbPq+YXhebuiYpPECIBrrKgFJoAQVATllKlB5RDQDTE4J84/8LwGfQqSxBiSK2u1aSaFpzgBVoBrKA=="], - - "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.0.1", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="], - - "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.0.1", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.0.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA=="], - - "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.34.0", "", {}, "sha512-aKcOkyrorBGlajjRdVoJWHTxfxO1vCNHLJVlSDaRHDIdjU+pX8IYQPvPDkYiujKLbRnWU+1TBwEt0QRgSm4SGA=="], - - "@opentelemetry/sql-common": ["@opentelemetry/sql-common@0.41.0", "", { "dependencies": { "@opentelemetry/core": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" } }, "sha512-pmzXctVbEERbqSfiAgdes9Y63xjoOyXcD7B6IXBkVb+vbM7M9U98mn33nGXxPf4dfYR0M+vhcKRZmbSJ7HfqFA=="], - - "@phala/dstack-sdk": ["@phala/dstack-sdk@0.1.11", "", { "optionalDependencies": { "@noble/curves": "^1.8.1", "@solana/web3.js": "^1.98.0", "viem": "^2.21.0 <3.0.0" } }, "sha512-d1naX/bDGqCItpIzvvHSpytNR9zNPofYbsCJD7uy2zT+vDC5lLehqL2BeR1d7QVsnnNI0wXPiXTiMbwGS7fz0Q=="], - - "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="], - - "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="], - - "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], - - "@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="], - - "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="], - - "@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="], - - "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="], - - "@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="], - - "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="], - - "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="], - - "@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="], - - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.40.2", "", { "os": "android", "cpu": "arm" }, "sha512-JkdNEq+DFxZfUwxvB58tHMHBHVgX23ew41g1OQinthJ+ryhdRk67O31S7sYw8u2lTjHUPFxwar07BBt1KHp/hg=="], - - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.40.2", "", { "os": "android", "cpu": "arm64" }, "sha512-13unNoZ8NzUmnndhPTkWPWbX3vtHodYmy+I9kuLxN+F+l+x3LdVF7UCu8TWVMt1POHLh6oDHhnOA04n8oJZhBw=="], - - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.40.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Gzf1Hn2Aoe8VZzevHostPX23U7N5+4D36WJNHK88NZHCJr7aVMG4fadqkIf72eqVPGjGc0HJHNuUaUcxiR+N/w=="], - - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.40.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-47N4hxa01a4x6XnJoskMKTS8XZ0CZMd8YTbINbi+w03A2w4j1RTlnGHOz/P0+Bg1LaVL6ufZyNprSg+fW5nYQQ=="], - - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.40.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-8t6aL4MD+rXSHHZUR1z19+9OFJ2rl1wGKvckN47XFRVO+QL/dUSpKA2SLRo4vMg7ELA8pzGpC+W9OEd1Z/ZqoQ=="], - - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.40.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-C+AyHBzfpsOEYRFjztcYUFsH4S7UsE9cDtHCtma5BK8+ydOZYgMmWg1d/4KBytQspJCld8ZIujFMAdKG1xyr4Q=="], - - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.40.2", "", { "os": "linux", "cpu": "arm" }, "sha512-de6TFZYIvJwRNjmW3+gaXiZ2DaWL5D5yGmSYzkdzjBDS3W+B9JQ48oZEsmMvemqjtAFzE16DIBLqd6IQQRuG9Q=="], - - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.40.2", "", { "os": "linux", "cpu": "arm" }, "sha512-urjaEZubdIkacKc930hUDOfQPysezKla/O9qV+O89enqsqUmQm8Xj8O/vh0gHg4LYfv7Y7UsE3QjzLQzDYN1qg=="], - - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.40.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-KlE8IC0HFOC33taNt1zR8qNlBYHj31qGT1UqWqtvR/+NuCVhfufAq9fxO8BMFC22Wu0rxOwGVWxtCMvZVLmhQg=="], - - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.40.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-j8CgxvfM0kbnhu4XgjnCWJQyyBOeBI1Zq91Z850aUddUmPeQvuAy6OiMdPS46gNFgy8gN1xkYyLgwLYZG3rBOg=="], - - "@rollup/rollup-linux-loongarch64-gnu": ["@rollup/rollup-linux-loongarch64-gnu@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-Ybc/1qUampKuRF4tQXc7G7QY9YRyeVSykfK36Y5Qc5dmrIxwFhrOzqaVTNoZygqZ1ZieSWTibfFhQ5qK8jpWxw=="], - - "@rollup/rollup-linux-powerpc64le-gnu": ["@rollup/rollup-linux-powerpc64le-gnu@4.40.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3FCIrnrt03CCsZqSYAOW/k9n625pjpuMzVfeI+ZBUSDT3MVIFDSPfSUgIl9FqUftxcUXInvFah79hE1c9abD+Q=="], - - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-QNU7BFHEvHMp2ESSY3SozIkBPaPBDTsfVNGx3Xhv+TdvWXFGOSH2NJvhD1zKAT6AyuuErJgbdvaJhYVhVqrWTg=="], - - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.40.2", "", { "os": "linux", "cpu": "none" }, "sha512-5W6vNYkhgfh7URiXTO1E9a0cy4fSgfE4+Hl5agb/U1sa0kjOLMLC1wObxwKxecE17j0URxuTrYZZME4/VH57Hg=="], - - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.40.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-B7LKIz+0+p348JoAL4X/YxGx9zOx3sR+o6Hj15Y3aaApNfAshK8+mWZEf759DXfRLeL2vg5LYJBB7DdcleYCoQ=="], - - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.40.2", "", { "os": "linux", "cpu": "x64" }, "sha512-lG7Xa+BmBNwpjmVUbmyKxdQJ3Q6whHjMjzQplOs5Z+Gj7mxPtWakGHqzMqNER68G67kmCX9qX57aRsW5V0VOng=="], - - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.40.2", "", { "os": "linux", "cpu": "x64" }, "sha512-tD46wKHd+KJvsmije4bUskNuvWKFcTOIM9tZ/RrmIvcXnbi0YK/cKS9FzFtAm7Oxi2EhV5N2OpfFB348vSQRXA=="], - - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.40.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Bjv/HG8RRWLNkXwQQemdsWw4Mg+IJ29LK+bJPW2SCzPKOUaMmPEppQlu/Fqk1d7+DX3V7JbFdbkh/NMmurT6Pg=="], - - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.40.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-dt1llVSGEsGKvzeIO76HToiYPNPYPkmjhMHhP00T9S4rDern8P2ZWvWAQUEJ+R1UdMWJ/42i/QqJ2WV765GZcA=="], - - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.40.2", "", { "os": "win32", "cpu": "x64" }, "sha512-bwspbWB04XJpeElvsp+DCylKfF4trJDa2Y9Go8O6A7YLX2LIKGcNK/CYImJN6ZP4DcuOHB4Utl3iCbnR62DudA=="], - - "@scure/base": ["@scure/base@1.2.5", "", {}, "sha512-9rE6EOVeIQzt5TSu4v+K523F8u6DhBsoZWPGKlnCshhlDhy0kJzUX4V+tr2dWmzF1GdekvThABoEQBGBQI7xZw=="], - - "@scure/bip32": ["@scure/bip32@1.6.2", "", { "dependencies": { "@noble/curves": "~1.8.1", "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.2" } }, "sha512-t96EPDMbtGgtb7onKKqxRLfE5g05k7uHnHRM2xdE6BP/ZmxaLtPek4J4KfVn/90IQNrU1IOAqMgiDtUdtbe3nw=="], - - "@scure/bip39": ["@scure/bip39@1.5.4", "", { "dependencies": { "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.4" } }, "sha512-TFM4ni0vKvCfBpohoh+/lY05i9gRbSwXWngAsF4CABQxoaOHijxuaZ2R6cStDQ5CHtHO9aGJTr4ksVJASRRyMA=="], - - "@solana/buffer-layout": ["@solana/buffer-layout@4.0.1", "", { "dependencies": { "buffer": "~6.0.3" } }, "sha512-E1ImOIAD1tBZFRdjeM4/pzTiTApC0AOBGwyAMS4fwIodCWArzJ3DWdoh8cKxeFM2fElkxBh2Aqts1BPC373rHA=="], - - "@solana/codecs-core": ["@solana/codecs-core@2.1.1", "", { "dependencies": { "@solana/errors": "2.1.1" }, "peerDependencies": { "typescript": ">=5.3.3" } }, "sha512-iPQW3UZ2Vi7QFBo2r9tw0NubtH8EdrhhmZulx6lC8V5a+qjaxovtM/q/UW2BTNpqqHLfO0tIcLyBLrNH4HTWPg=="], - - "@solana/codecs-numbers": ["@solana/codecs-numbers@2.1.1", "", { "dependencies": { "@solana/codecs-core": "2.1.1", "@solana/errors": "2.1.1" }, "peerDependencies": { "typescript": ">=5.3.3" } }, "sha512-m20IUPJhPUmPkHSlZ2iMAjJ7PaYUvlMtFhCQYzm9BEBSI6OCvXTG3GAPpAnSGRBfg5y+QNqqmKn4QHU3B6zzCQ=="], - - "@solana/errors": ["@solana/errors@2.1.1", "", { "dependencies": { "chalk": "^5.4.1", "commander": "^13.1.0" }, "peerDependencies": { "typescript": ">=5.3.3" }, "bin": { "errors": "bin/cli.mjs" } }, "sha512-sj6DaWNbSJFvLzT8UZoabMefQUfSW/8tXK7NTiagsDmh+Q87eyQDDC9L3z+mNmx9b6dEf6z660MOIplDD2nfEw=="], - - "@solana/web3.js": ["@solana/web3.js@1.98.2", "", { "dependencies": { "@babel/runtime": "^7.25.0", "@noble/curves": "^1.4.2", "@noble/hashes": "^1.4.0", "@solana/buffer-layout": "^4.0.1", "@solana/codecs-numbers": "^2.1.0", "agentkeepalive": "^4.5.0", "bn.js": "^5.2.1", "borsh": "^0.7.0", "bs58": "^4.0.1", "buffer": "6.0.3", "fast-stable-stringify": "^1.0.0", "jayson": "^4.1.1", "node-fetch": "^2.7.0", "rpc-websockets": "^9.0.2", "superstruct": "^2.0.2" } }, "sha512-BqVwEG+TaG2yCkBMbD3C4hdpustR4FpuUFRPUmqRZYYlPI9Hg4XMWxHWOWRzHE9Lkc9NDjzXFX7lDXSgzC7R1A=="], - - "@swc/helpers": ["@swc/helpers@0.5.17", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A=="], - - "@types/connect": ["@types/connect@3.4.38", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="], - - "@types/estree": ["@types/estree@1.0.7", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="], - - "@types/node": ["@types/node@22.15.18", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-v1DKRfUdyW+jJhZNEI1PYy29S2YRxMV5AOO/x/SjKmW0acCIOqmbj6Haf9eHAhsPmrhlHSxEhv/1WszcLWV4cg=="], - - "@types/node-fetch": ["@types/node-fetch@2.6.12", "", { "dependencies": { "@types/node": "*", "form-data": "^4.0.0" } }, "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA=="], - - "@types/pg": ["@types/pg@8.6.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-1Kc4oAGzAl7uqUStZCDvaLFqZrW9qWSjXOmBfdgyBP5La7Us6Mg4GBvRlSoaZMhQF/zSj1C8CtKMBkoiT8eL8w=="], - - "@types/pg-pool": ["@types/pg-pool@2.0.6", "", { "dependencies": { "@types/pg": "*" } }, "sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ=="], - - "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], - - "@types/shimmer": ["@types/shimmer@1.2.0", "", {}, "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg=="], - - "@types/uuid": ["@types/uuid@8.3.4", "", {}, "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw=="], - - "@types/ws": ["@types/ws@7.4.7", "", { "dependencies": { "@types/node": "*" } }, "sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww=="], - - "@vitest/expect": ["@vitest/expect@3.1.3", "", { "dependencies": { "@vitest/spy": "3.1.3", "@vitest/utils": "3.1.3", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-7FTQQuuLKmN1Ig/h+h/GO+44Q1IlglPlR2es4ab7Yvfx+Uk5xsv+Ykk+MEt/M2Yn/xGmzaLKxGw2lgy2bwuYqg=="], - - "@vitest/mocker": ["@vitest/mocker@3.1.3", "", { "dependencies": { "@vitest/spy": "3.1.3", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-PJbLjonJK82uCWHjzgBJZuR7zmAOrSvKk1QBxrennDIgtH4uK0TB1PvYmc0XBCigxxtiAVPfWtAdy4lpz8SQGQ=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@3.1.3", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-i6FDiBeJUGLDKADw2Gb01UtUNb12yyXAqC/mmRWuYl+m/U9GS7s8us5ONmGkGpUUo7/iAYzI2ePVfOZTYvUifA=="], - - "@vitest/runner": ["@vitest/runner@3.1.3", "", { "dependencies": { "@vitest/utils": "3.1.3", "pathe": "^2.0.3" } }, "sha512-Tae+ogtlNfFei5DggOsSUvkIaSuVywujMj6HzR97AHK6XK8i3BuVyIifWAm/sE3a15lF5RH9yQIrbXYuo0IFyA=="], - - "@vitest/snapshot": ["@vitest/snapshot@3.1.3", "", { "dependencies": { "@vitest/pretty-format": "3.1.3", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-XVa5OPNTYUsyqG9skuUkFzAeFnEzDp8hQu7kZ0N25B1+6KjGm4hWLtURyBbsIAOekfWQ7Wuz/N/XXzgYO3deWQ=="], - - "@vitest/spy": ["@vitest/spy@3.1.3", "", { "dependencies": { "tinyspy": "^3.0.2" } }, "sha512-x6w+ctOEmEXdWaa6TO4ilb7l9DxPR5bwEb6hILKuxfU1NqWT2mpJD9NJN7t3OTfxmVlOMrvtoFJGdgyzZ605lQ=="], - - "@vitest/utils": ["@vitest/utils@3.1.3", "", { "dependencies": { "@vitest/pretty-format": "3.1.3", "loupe": "^3.1.3", "tinyrainbow": "^2.0.0" } }, "sha512-2Ltrpht4OmHO9+c/nmHtF09HWiyWdworqnHIwjfvDyWjuwKbdkcS9AnhsDn+8E2RM4x++foD1/tNuLPVvWG1Rg=="], - - "abitype": ["abitype@1.0.8", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3 >=3.22.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-ZeiI6h3GnW06uYDLx0etQtX/p8E24UaHHBj57RSjK7YBFe7iuVn07EDpOeP451D06sF27VOz9JJPlIKJmXgkEg=="], - - "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], - - "acorn": ["acorn@8.14.1", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg=="], - - "acorn-import-attributes": ["acorn-import-attributes@1.9.5", "", { "peerDependencies": { "acorn": "^8" } }, "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ=="], - - "agentkeepalive": ["agentkeepalive@4.6.0", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="], - - "ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], - - "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], - - "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], - - "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], - - "asn1.js": ["asn1.js@4.10.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw=="], - - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], - - "atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="], - - "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - - "base-x": ["base-x@3.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-xz7wQ8xDhdyP7tQxwdteLYeFfS68tSMNCZ/Y37WJ4bhGfKPpqEIlmIyueQHqOyoPhE6xNUqjzRr8ra0eF9VRvA=="], - - "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - - "bn.js": ["bn.js@5.2.2", "", {}, "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw=="], - - "borsh": ["borsh@0.7.0", "", { "dependencies": { "bn.js": "^5.2.0", "bs58": "^4.0.0", "text-encoding-utf-8": "^1.0.2" } }, "sha512-CLCsZGIBCFnPtkNnieW/a8wmreDmfUtjU2m9yHrzPXIlNbqVs0AQrSatSG6vdNYUqdc83tkQi2eHfF98ubzQLA=="], - - "brace-expansion": ["brace-expansion@2.0.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="], - - "brorand": ["brorand@1.1.0", "", {}, "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w=="], - - "browserify-aes": ["browserify-aes@1.2.0", "", { "dependencies": { "buffer-xor": "^1.0.3", "cipher-base": "^1.0.0", "create-hash": "^1.1.0", "evp_bytestokey": "^1.0.3", "inherits": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA=="], - - "browserify-cipher": ["browserify-cipher@1.0.1", "", { "dependencies": { "browserify-aes": "^1.0.4", "browserify-des": "^1.0.0", "evp_bytestokey": "^1.0.0" } }, "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w=="], - - "browserify-des": ["browserify-des@1.0.2", "", { "dependencies": { "cipher-base": "^1.0.1", "des.js": "^1.0.0", "inherits": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A=="], - - "browserify-rsa": ["browserify-rsa@4.1.1", "", { "dependencies": { "bn.js": "^5.2.1", "randombytes": "^2.1.0", "safe-buffer": "^5.2.1" } }, "sha512-YBjSAiTqM04ZVei6sXighu679a3SqWORA3qZTEqZImnlkDIFtKc6pNutpjyZ8RJTjQtuYfeetkxM11GwoYXMIQ=="], - - "browserify-sign": ["browserify-sign@4.2.3", "", { "dependencies": { "bn.js": "^5.2.1", "browserify-rsa": "^4.1.0", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", "elliptic": "^6.5.5", "hash-base": "~3.0", "inherits": "^2.0.4", "parse-asn1": "^5.1.7", "readable-stream": "^2.3.8", "safe-buffer": "^5.2.1" } }, "sha512-JWCZW6SKhfhjJxO8Tyiiy+XYB7cqd2S5/+WeYHsKdNKFlCBhKbblba1A/HN/90YwtxKc8tCErjffZl++UNmGiw=="], - - "bs58": ["bs58@4.0.1", "", { "dependencies": { "base-x": "^3.0.2" } }, "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw=="], - - "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], - - "buffer-xor": ["buffer-xor@1.0.3", "", {}, "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ=="], - - "bufferutil": ["bufferutil@4.0.9", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-WDtdLmJvAuNNPzByAYpRo2rF1Mmradw6gvWsQKf63476DDXmomT9zUiGypLcG4ibIM67vhAj8jJRdbmEws2Aqw=="], - - "bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="], - - "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], - - "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], - - "camelcase": ["camelcase@6.3.0", "", {}, "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA=="], - - "chai": ["chai@5.2.0", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw=="], - - "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - - "check-error": ["check-error@2.1.1", "", {}, "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw=="], - - "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], - - "cipher-base": ["cipher-base@1.0.6", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1" } }, "sha512-3Ek9H3X6pj5TgenXYtNWdaBon1tgYCaebd+XPg0keyjEbEfkD4KkmAxkQ/i1vYvxdcT5nscLBfq9VJRmCBcFSw=="], - - "cjs-module-lexer": ["cjs-module-lexer@1.4.3", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="], - - "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], - - "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], - - "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], - - "colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="], - - "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], - - "commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], - - "confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="], - - "consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="], - - "console-table-printer": ["console-table-printer@2.12.1", "", { "dependencies": { "simple-wcswidth": "^1.0.1" } }, "sha512-wKGOQRRvdnd89pCeH96e2Fn4wkbenSP6LMHfjfyNLMbGuHEFbMqQNuxXqd0oXG9caIOQ1FTvc5Uijp9/4jujnQ=="], - - "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], - - "create-ecdh": ["create-ecdh@4.0.4", "", { "dependencies": { "bn.js": "^4.1.0", "elliptic": "^6.5.3" } }, "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A=="], - - "create-hash": ["create-hash@1.2.0", "", { "dependencies": { "cipher-base": "^1.0.1", "inherits": "^2.0.1", "md5.js": "^1.3.4", "ripemd160": "^2.0.1", "sha.js": "^2.4.0" } }, "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg=="], - - "create-hmac": ["create-hmac@1.1.7", "", { "dependencies": { "cipher-base": "^1.0.3", "create-hash": "^1.1.0", "inherits": "^2.0.1", "ripemd160": "^2.0.0", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg=="], - - "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], - - "crypto-browserify": ["crypto-browserify@3.12.1", "", { "dependencies": { "browserify-cipher": "^1.0.1", "browserify-sign": "^4.2.3", "create-ecdh": "^4.0.4", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", "diffie-hellman": "^5.0.3", "hash-base": "~3.0.4", "inherits": "^2.0.4", "pbkdf2": "^3.1.2", "public-encrypt": "^4.0.3", "randombytes": "^2.1.0", "randomfill": "^1.0.4" } }, "sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ=="], - - "dateformat": ["dateformat@4.6.3", "", {}, "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA=="], - - "debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="], - - "decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="], - - "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], - - "delay": ["delay@5.0.0", "", {}, "sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw=="], - - "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], - - "des.js": ["des.js@1.1.0", "", { "dependencies": { "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg=="], - - "diffie-hellman": ["diffie-hellman@5.0.3", "", { "dependencies": { "bn.js": "^4.1.0", "miller-rabin": "^4.0.0", "randombytes": "^2.0.0" } }, "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg=="], - - "dotenv": ["dotenv@16.4.5", "", {}, "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg=="], - - "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], - - "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], - - "elliptic": ["elliptic@6.6.1", "", { "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", "inherits": "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g=="], - - "emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], - - "end-of-stream": ["end-of-stream@1.4.4", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q=="], - - "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], - - "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], - - "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], - - "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], - - "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], - - "es6-promise": ["es6-promise@4.2.8", "", {}, "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w=="], - - "es6-promisify": ["es6-promisify@5.0.0", "", { "dependencies": { "es6-promise": "^4.0.3" } }, "sha512-C+d6UdsYDk0lMebHNR4S2NybQMMngAOnOwYBQjTOiv0MkoJMP0Myw2mgpDLBcpfCmRLxyFqYhS/CfOENq4SJhQ=="], - - "esbuild": ["esbuild@0.25.4", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.4", "@esbuild/android-arm": "0.25.4", "@esbuild/android-arm64": "0.25.4", "@esbuild/android-x64": "0.25.4", "@esbuild/darwin-arm64": "0.25.4", "@esbuild/darwin-x64": "0.25.4", "@esbuild/freebsd-arm64": "0.25.4", "@esbuild/freebsd-x64": "0.25.4", "@esbuild/linux-arm": "0.25.4", "@esbuild/linux-arm64": "0.25.4", "@esbuild/linux-ia32": "0.25.4", "@esbuild/linux-loong64": "0.25.4", "@esbuild/linux-mips64el": "0.25.4", "@esbuild/linux-ppc64": "0.25.4", "@esbuild/linux-riscv64": "0.25.4", "@esbuild/linux-s390x": "0.25.4", "@esbuild/linux-x64": "0.25.4", "@esbuild/netbsd-arm64": "0.25.4", "@esbuild/netbsd-x64": "0.25.4", "@esbuild/openbsd-arm64": "0.25.4", "@esbuild/openbsd-x64": "0.25.4", "@esbuild/sunos-x64": "0.25.4", "@esbuild/win32-arm64": "0.25.4", "@esbuild/win32-ia32": "0.25.4", "@esbuild/win32-x64": "0.25.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q=="], - - "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], - - "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - - "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], - - "eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], - - "events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="], - - "evp_bytestokey": ["evp_bytestokey@1.0.3", "", { "dependencies": { "md5.js": "^1.3.4", "safe-buffer": "^5.1.1" } }, "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA=="], - - "expect-type": ["expect-type@1.2.1", "", {}, "sha512-/kP8CAwxzLVEeFrMm4kMmy4CCDlpipyA7MYLVrdJIkV0fYF0UaigQHRsxHiuY/GEea+bh4KSv3TIlgr+2UL6bw=="], - - "eyes": ["eyes@0.1.8", "", {}, "sha512-GipyPsXO1anza0AOZdy69Im7hGFCNB7Y/NGjDlZGJ3GJJLtwNSb2vrzYrTYJRrRloVx7pl+bhUaTB8yiccPvFQ=="], - - "fast-copy": ["fast-copy@3.0.2", "", {}, "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ=="], - - "fast-redact": ["fast-redact@3.5.0", "", {}, "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A=="], - - "fast-safe-stringify": ["fast-safe-stringify@2.1.1", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="], - - "fast-stable-stringify": ["fast-stable-stringify@1.0.0", "", {}, "sha512-wpYMUmFu5f00Sm0cj2pfivpmawLZ0NKdviQ4w9zJeR8JVtOpOxHmLaJuj0vxvGqMJQWyP/COUkF75/57OKyRag=="], - - "fdir": ["fdir@6.4.4", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg=="], - - "fix-dts-default-cjs-exports": ["fix-dts-default-cjs-exports@1.0.1", "", { "dependencies": { "magic-string": "^0.30.17", "mlly": "^1.7.4", "rollup": "^4.34.8" } }, "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg=="], - - "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], - - "form-data": ["form-data@4.0.2", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "mime-types": "^2.1.12" } }, "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w=="], - - "form-data-encoder": ["form-data-encoder@1.7.2", "", {}, "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="], - - "formdata-node": ["formdata-node@4.4.1", "", { "dependencies": { "node-domexception": "1.0.0", "web-streams-polyfill": "4.0.0-beta.3" } }, "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], - - "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], - - "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], - - "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], - - "glob": ["glob@11.0.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^4.0.1", "minimatch": "^10.0.0", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-9UiX/Bl6J2yaBbxKoEBRm4Cipxgok8kQYcOPEhScPwebu2I0HoQOuYdIO6S3hLuWoZgpDpwQZMzTFxgpkyT76g=="], - - "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], - - "handlebars": ["handlebars@4.7.8", "", { "dependencies": { "minimist": "^1.2.5", "neo-async": "^2.6.2", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "optionalDependencies": { "uglify-js": "^3.1.4" }, "bin": { "handlebars": "bin/handlebars" } }, "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ=="], - - "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], - - "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], - - "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], - - "hash-base": ["hash-base@3.0.5", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1" } }, "sha512-vXm0l45VbcHEVlTCzs8M+s0VeYsB2lnlAaThoLKGXr3bE/VWDOelNUnycUPEhKEaXARL2TEFjBOyUiM6+55KBg=="], - - "hash.js": ["hash.js@1.1.7", "", { "dependencies": { "inherits": "^2.0.3", "minimalistic-assert": "^1.0.1" } }, "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA=="], - - "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], - - "help-me": ["help-me@5.0.0", "", {}, "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="], - - "hmac-drbg": ["hmac-drbg@1.0.1", "", { "dependencies": { "hash.js": "^1.0.3", "minimalistic-assert": "^1.0.0", "minimalistic-crypto-utils": "^1.0.1" } }, "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg=="], - - "humanize-ms": ["humanize-ms@1.2.1", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="], - - "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - - "import-in-the-middle": ["import-in-the-middle@1.13.2", "", { "dependencies": { "acorn": "^8.14.0", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" } }, "sha512-Yjp9X7s2eHSXvZYQ0aye6UvwYPrVB5C2k47fuXjFKnYinAByaDZjh4t9MT2wEga9775n6WaIqyHnQhBxYtX2mg=="], - - "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - - "is-core-module": ["is-core-module@2.16.1", "", { "dependencies": { "hasown": "^2.0.2" } }, "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w=="], - - "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], - - "isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], - - "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - - "isomorphic-ws": ["isomorphic-ws@4.0.1", "", { "peerDependencies": { "ws": "*" } }, "sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w=="], - - "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], - - "jackspeak": ["jackspeak@4.1.0", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" } }, "sha512-9DDdhb5j6cpeitCbvLO7n7J4IxnbM6hoF6O1g4HQ5TfhvvKN8ywDM7668ZhMHRqVmxqhps/F6syWK2KcPxYlkw=="], - - "jayson": ["jayson@4.2.0", "", { "dependencies": { "@types/connect": "^3.4.33", "@types/node": "^12.12.54", "@types/ws": "^7.4.4", "commander": "^2.20.3", "delay": "^5.0.0", "es6-promisify": "^5.0.0", "eyes": "^0.1.8", "isomorphic-ws": "^4.0.1", "json-stringify-safe": "^5.0.1", "stream-json": "^1.9.1", "uuid": "^8.3.2", "ws": "^7.5.10" }, "bin": { "jayson": "bin/jayson.js" } }, "sha512-VfJ9t1YLwacIubLhONk0KFeosUBwstRWQ0IRT1KDjEjnVnSOVHC3uwugyV7L0c7R9lpVyrUGT2XWiBA1UTtpyg=="], - - "joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="], - - "js-sha1": ["js-sha1@0.7.0", "", {}, "sha512-oQZ1Mo7440BfLSv9TX87VNEyU52pXPVG19F9PL3gTgNt0tVxlZ8F4O6yze3CLuLx28TxotxvlyepCNaaV0ZjMw=="], - - "js-tiktoken": ["js-tiktoken@1.0.20", "", { "dependencies": { "base64-js": "^1.5.1" } }, "sha512-Xlaqhhs8VfCd6Sh7a1cFkZHQbYTLCwVJJWiHVxBYzLPxW0XsoxBy1hitmjkdIjD3Aon5BXLHFwU5O8WUx6HH+A=="], - - "js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="], - - "json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="], - - "jsonpointer": ["jsonpointer@5.0.1", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="], - - "langchain": ["langchain@0.3.26", "", { "dependencies": { "@langchain/openai": ">=0.1.0 <0.6.0", "@langchain/textsplitters": ">=0.0.0 <0.2.0", "js-tiktoken": "^1.0.12", "js-yaml": "^4.1.0", "jsonpointer": "^5.0.1", "langsmith": "^0.3.29", "openapi-types": "^12.1.3", "p-retry": "4", "uuid": "^10.0.0", "yaml": "^2.2.1", "zod": "^3.22.4", "zod-to-json-schema": "^3.22.3" }, "peerDependencies": { "@langchain/anthropic": "*", "@langchain/aws": "*", "@langchain/cerebras": "*", "@langchain/cohere": "*", "@langchain/core": ">=0.2.21 <0.4.0", "@langchain/deepseek": "*", "@langchain/google-genai": "*", "@langchain/google-vertexai": "*", "@langchain/google-vertexai-web": "*", "@langchain/groq": "*", "@langchain/mistralai": "*", "@langchain/ollama": "*", "@langchain/xai": "*", "axios": "*", "cheerio": "*", "handlebars": "^4.7.8", "peggy": "^3.0.2", "typeorm": "*" }, "optionalPeers": ["@langchain/anthropic", "@langchain/aws", "@langchain/cerebras", "@langchain/cohere", "@langchain/deepseek", "@langchain/google-genai", "@langchain/google-vertexai", "@langchain/google-vertexai-web", "@langchain/groq", "@langchain/mistralai", "@langchain/ollama", "@langchain/xai", "axios", "cheerio", "handlebars", "peggy", "typeorm"] }, "sha512-W/9phB4wiAnj+PnpMWmv/ptIp7i5ygY2aK8yjKlxccHPbaNeMoy7njzFz8d0/xfcPyA3MvG4AuZnJ1j3/E2/Ig=="], - - "langsmith": ["langsmith@0.3.29", "", { "dependencies": { "@types/uuid": "^10.0.0", "chalk": "^4.1.2", "console-table-printer": "^2.12.1", "p-queue": "^6.6.2", "p-retry": "4", "semver": "^7.6.3", "uuid": "^10.0.0" }, "peerDependencies": { "openai": "*" }, "optionalPeers": ["openai"] }, "sha512-JPF2B339qpYy9FyuY4Yz1aWYtgPlFc/a+VTj3L/JcFLHCiMP7+Ig8I9jO+o1QwVa+JU3iugL1RS0wwc+Glw0zA=="], - - "lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="], - - "lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="], - - "load-tsconfig": ["load-tsconfig@0.2.5", "", {}, "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg=="], - - "lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="], - - "lodash.sortby": ["lodash.sortby@4.7.0", "", {}, "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA=="], - - "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], - - "loupe": ["loupe@3.1.3", "", {}, "sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug=="], - - "lru-cache": ["lru-cache@11.1.0", "", {}, "sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A=="], - - "magic-string": ["magic-string@0.30.17", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="], - - "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], - - "md5.js": ["md5.js@1.3.5", "", { "dependencies": { "hash-base": "^3.0.0", "inherits": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg=="], - - "miller-rabin": ["miller-rabin@4.0.1", "", { "dependencies": { "bn.js": "^4.0.0", "brorand": "^1.0.1" }, "bin": { "miller-rabin": "bin/miller-rabin" } }, "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA=="], - - "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], - - "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - - "minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="], - - "minimalistic-crypto-utils": ["minimalistic-crypto-utils@1.0.1", "", {}, "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg=="], - - "minimatch": ["minimatch@10.0.1", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ=="], - - "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], - - "minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="], - - "mlly": ["mlly@1.7.4", "", { "dependencies": { "acorn": "^8.14.0", "pathe": "^2.0.1", "pkg-types": "^1.3.0", "ufo": "^1.5.4" } }, "sha512-qmdSIPC4bDJXgZTCR7XosJiNKySV7O215tsPtDN9iEO/7q/76b/ijtgRu/+epFXSJhijtTCCGp3DWS549P3xKw=="], - - "module-details-from-path": ["module-details-from-path@1.0.4", "", {}, "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w=="], - - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "mustache": ["mustache@4.2.0", "", { "bin": { "mustache": "bin/mustache" } }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="], - - "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], - - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - - "neo-async": ["neo-async@2.6.2", "", {}, "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw=="], - - "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], - - "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], - - "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], - - "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], - - "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], - - "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], - - "openai": ["openai@4.100.0", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" }, "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-9soq/wukv3utxcuD7TWFqKdKp0INWdeyhUCvxwrne5KwnxaCp4eHL4GdT/tMFhYolxgNhxFzg5GFwM331Z5CZg=="], - - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - - "ox": ["ox@0.6.9", "", { "dependencies": { "@adraffy/ens-normalize": "^1.10.1", "@noble/curves": "^1.6.0", "@noble/hashes": "^1.5.0", "@scure/bip32": "^1.5.0", "@scure/bip39": "^1.4.0", "abitype": "^1.0.6", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug=="], - - "p-finally": ["p-finally@1.0.0", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="], - - "p-queue": ["p-queue@6.6.2", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="], - - "p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="], - - "p-timeout": ["p-timeout@3.2.0", "", { "dependencies": { "p-finally": "^1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="], - - "package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="], - - "parse-asn1": ["parse-asn1@5.1.7", "", { "dependencies": { "asn1.js": "^4.10.1", "browserify-aes": "^1.2.0", "evp_bytestokey": "^1.0.3", "hash-base": "~3.0", "pbkdf2": "^3.1.2", "safe-buffer": "^5.2.1" } }, "sha512-CTM5kuWR3sx9IFamcl5ErfPl6ea/N8IYwiJ+vpeB2g+1iknv7zBl5uPwbMbRVznRVbrNY6lGuDoE5b30grmbqg=="], - - "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], - - "path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="], - - "path-scurry": ["path-scurry@2.0.0", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg=="], - - "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "pathval": ["pathval@2.0.0", "", {}, "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA=="], - - "pbkdf2": ["pbkdf2@3.1.2", "", { "dependencies": { "create-hash": "^1.1.2", "create-hmac": "^1.1.4", "ripemd160": "^2.0.1", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA=="], - - "pdfjs-dist": ["pdfjs-dist@5.2.133", "", { "optionalDependencies": { "@napi-rs/canvas": "^0.1.67" } }, "sha512-abE6ZWDxztt+gGFzfm4bX2ggfxUk9wsDEoFzIJm9LozaY3JdXR7jyLK4Bjs+XLXplCduuWS1wGhPC4tgTn/kzg=="], - - "pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="], - - "pg-protocol": ["pg-protocol@1.10.0", "", {}, "sha512-IpdytjudNuLv8nhlHs/UrVBhU0e78J0oIS/0AVdTbWxSOkFUVdsHC/NrorO6nXsQNDTT1kzDSOMJubBQviX18Q=="], - - "pg-types": ["pg-types@2.2.0", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="], - - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - - "picomatch": ["picomatch@4.0.2", "", {}, "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg=="], - - "pino": ["pino@9.6.0", "", { "dependencies": { "atomic-sleep": "^1.0.0", "fast-redact": "^3.1.1", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^4.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^3.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-i85pKRCt4qMjZ1+L7sy2Ag4t1atFcdbEt76+7iRJn1g2BvsnRMGu9p8pivl9fs63M2kF/A0OacFZhTub+m/qMg=="], - - "pino-abstract-transport": ["pino-abstract-transport@2.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw=="], - - "pino-pretty": ["pino-pretty@13.0.0", "", { "dependencies": { "colorette": "^2.0.7", "dateformat": "^4.6.3", "fast-copy": "^3.0.2", "fast-safe-stringify": "^2.1.1", "help-me": "^5.0.0", "joycon": "^3.1.1", "minimist": "^1.2.6", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pump": "^3.0.0", "secure-json-parse": "^2.4.0", "sonic-boom": "^4.0.1", "strip-json-comments": "^3.1.1" }, "bin": { "pino-pretty": "bin.js" } }, "sha512-cQBBIVG3YajgoUjo1FdKVRX6t9XPxwB9lcNJVD5GCnNM4Y6T12YYx8c6zEejxQsU0wrg9TwmDulcE9LR7qcJqA=="], - - "pino-std-serializers": ["pino-std-serializers@7.0.0", "", {}, "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA=="], - - "pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="], - - "pkg-types": ["pkg-types@1.3.1", "", { "dependencies": { "confbox": "^0.1.8", "mlly": "^1.7.4", "pathe": "^2.0.1" } }, "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ=="], - - "postcss": ["postcss@8.5.3", "", { "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A=="], - - "postcss-load-config": ["postcss-load-config@6.0.1", "", { "dependencies": { "lilconfig": "^3.1.1" }, "peerDependencies": { "jiti": ">=1.21.0", "postcss": ">=8.0.9", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "postcss", "tsx", "yaml"] }, "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g=="], - - "postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="], - - "postgres-bytea": ["postgres-bytea@1.0.0", "", {}, "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w=="], - - "postgres-date": ["postgres-date@1.0.7", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="], - - "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], - - "prettier": ["prettier@3.5.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw=="], - - "process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="], - - "process-warning": ["process-warning@4.0.1", "", {}, "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q=="], - - "protobufjs": ["protobufjs@7.5.2", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-f2ls6rpO6G153Cy+o2XQ+Y0sARLOZ17+OGVLHrc3VUKcLHYKEKWbkSujdBWQXM7gKn5NTfp0XnRPZn1MIu8n9w=="], - - "public-encrypt": ["public-encrypt@4.0.3", "", { "dependencies": { "bn.js": "^4.1.0", "browserify-rsa": "^4.0.0", "create-hash": "^1.1.0", "parse-asn1": "^5.0.0", "randombytes": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q=="], - - "pump": ["pump@3.0.2", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw=="], - - "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], - - "quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="], - - "randombytes": ["randombytes@2.1.0", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="], - - "randomfill": ["randomfill@1.0.4", "", { "dependencies": { "randombytes": "^2.0.5", "safe-buffer": "^5.1.0" } }, "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw=="], - - "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], - - "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], - - "real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="], - - "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], - - "require-in-the-middle": ["require-in-the-middle@7.5.2", "", { "dependencies": { "debug": "^4.3.5", "module-details-from-path": "^1.0.3", "resolve": "^1.22.8" } }, "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ=="], - - "resolve": ["resolve@1.22.10", "", { "dependencies": { "is-core-module": "^2.16.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w=="], - - "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], - - "retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], - - "ripemd160": ["ripemd160@2.0.2", "", { "dependencies": { "hash-base": "^3.0.0", "inherits": "^2.0.1" } }, "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA=="], - - "rollup": ["rollup@4.40.2", "", { "dependencies": { "@types/estree": "1.0.7" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.40.2", "@rollup/rollup-android-arm64": "4.40.2", "@rollup/rollup-darwin-arm64": "4.40.2", "@rollup/rollup-darwin-x64": "4.40.2", "@rollup/rollup-freebsd-arm64": "4.40.2", "@rollup/rollup-freebsd-x64": "4.40.2", "@rollup/rollup-linux-arm-gnueabihf": "4.40.2", "@rollup/rollup-linux-arm-musleabihf": "4.40.2", "@rollup/rollup-linux-arm64-gnu": "4.40.2", "@rollup/rollup-linux-arm64-musl": "4.40.2", "@rollup/rollup-linux-loongarch64-gnu": "4.40.2", "@rollup/rollup-linux-powerpc64le-gnu": "4.40.2", "@rollup/rollup-linux-riscv64-gnu": "4.40.2", "@rollup/rollup-linux-riscv64-musl": "4.40.2", "@rollup/rollup-linux-s390x-gnu": "4.40.2", "@rollup/rollup-linux-x64-gnu": "4.40.2", "@rollup/rollup-linux-x64-musl": "4.40.2", "@rollup/rollup-win32-arm64-msvc": "4.40.2", "@rollup/rollup-win32-ia32-msvc": "4.40.2", "@rollup/rollup-win32-x64-msvc": "4.40.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-tfUOg6DTP4rhQ3VjOO6B4wyrJnGOX85requAXvqYTHsOgb2TFJdZ3aWpT8W2kPoypSGP7dZUyzxJ9ee4buM5Fg=="], - - "rpc-websockets": ["rpc-websockets@9.1.1", "", { "dependencies": { "@swc/helpers": "^0.5.11", "@types/uuid": "^8.3.4", "@types/ws": "^8.2.2", "buffer": "^6.0.3", "eventemitter3": "^5.0.1", "uuid": "^8.3.2", "ws": "^8.5.0" }, "optionalDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" } }, "sha512-1IXGM/TfPT6nfYMIXkJdzn+L4JEsmb0FL1O2OBjaH03V3yuUDdKFulGLMFG6ErV+8pZ5HVC0limve01RyO+saA=="], - - "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], - - "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], - - "secure-json-parse": ["secure-json-parse@2.7.0", "", {}, "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="], - - "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], - - "sha.js": ["sha.js@2.4.11", "", { "dependencies": { "inherits": "^2.0.1", "safe-buffer": "^5.0.1" }, "bin": { "sha.js": "./bin.js" } }, "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ=="], - - "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], - - "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], - - "shimmer": ["shimmer@1.2.1", "", {}, "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - - "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], - - "simple-wcswidth": ["simple-wcswidth@1.0.1", "", {}, "sha512-xMO/8eNREtaROt7tJvWJqHBDTMFN4eiQ5I4JRMuilwfnFcV5W9u7RUkueNkdw0jPqGMX36iCywelS5yilTuOxg=="], - - "sonic-boom": ["sonic-boom@4.2.0", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww=="], - - "source-map": ["source-map@0.8.0-beta.0", "", { "dependencies": { "whatwg-url": "^7.0.0" } }, "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA=="], - - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@3.9.0", "", {}, "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw=="], - - "stream-browserify": ["stream-browserify@3.0.0", "", { "dependencies": { "inherits": "~2.0.4", "readable-stream": "^3.5.0" } }, "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA=="], - - "stream-chain": ["stream-chain@2.2.5", "", {}, "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA=="], - - "stream-json": ["stream-json@1.9.1", "", { "dependencies": { "stream-chain": "^2.2.5" } }, "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw=="], - - "string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], - - "string-width-cjs": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - - "string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], - - "strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="], - - "strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="], - - "sucrase": ["sucrase@3.35.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "glob": "^10.3.10", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA=="], - - "superstruct": ["superstruct@2.0.2", "", {}, "sha512-uV+TFRZdXsqXTL2pRvujROjdZQ4RAlBUS5BTh9IGm+jTqQntYThciG/qu57Gs69yjnVUSqdxF9YLmSnpupBW9A=="], - - "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], - - "supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="], - - "text-encoding-utf-8": ["text-encoding-utf-8@1.0.2", "", {}, "sha512-8bw4MY9WjdsD2aMtO0OzOCY3pXGYNx2d2FfHRVUKkiCPDWjKuOlhLVASS+pD7VkLTVjW268LYJHwsnPFlBpbAg=="], - - "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], - - "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], - - "thread-stream": ["thread-stream@3.1.0", "", { "dependencies": { "real-require": "^0.2.0" } }, "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - - "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], - - "tinyglobby": ["tinyglobby@0.2.13", "", { "dependencies": { "fdir": "^6.4.4", "picomatch": "^4.0.2" } }, "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw=="], - - "tinypool": ["tinypool@1.0.2", "", {}, "sha512-al6n+QEANGFOMf/dmUMsuS5/r9B06uwlyNjZZql/zv8J7ybHCgoihBNORZCY2mzUuAnomQa2JdhyHKzZxPCrFA=="], - - "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], - - "tinyspy": ["tinyspy@3.0.2", "", {}, "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q=="], - - "tr46": ["tr46@1.0.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA=="], - - "tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="], - - "ts-interface-checker": ["ts-interface-checker@0.1.13", "", {}, "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="], - - "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - - "tsup": ["tsup@8.5.0", "", { "dependencies": { "bundle-require": "^5.1.0", "cac": "^6.7.14", "chokidar": "^4.0.3", "consola": "^3.4.0", "debug": "^4.4.0", "esbuild": "^0.25.0", "fix-dts-default-cjs-exports": "^1.0.0", "joycon": "^3.1.1", "picocolors": "^1.1.1", "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", "rollup": "^4.34.8", "source-map": "0.8.0-beta.0", "sucrase": "^3.35.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "peerDependencies": { "@microsoft/api-extractor": "^7.36.0", "@swc/core": "^1", "postcss": "^8.4.12", "typescript": ">=4.5.0" }, "optionalPeers": ["@microsoft/api-extractor", "@swc/core", "postcss", "typescript"], "bin": { "tsup": "dist/cli-default.js", "tsup-node": "dist/cli-node.js" } }, "sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ=="], - - "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "ufo": ["ufo@1.6.1", "", {}, "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA=="], - - "uglify-js": ["uglify-js@3.19.3", "", { "bin": { "uglifyjs": "bin/uglifyjs" } }, "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ=="], - - "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], - - "unique-names-generator": ["unique-names-generator@4.7.1", "", {}, "sha512-lMx9dX+KRmG8sq6gulYYpKWZc9RlGsgBR6aoO8Qsm3qvkSJ+3rAymr+TnV8EDMrIrwuFJ4kruzMWM/OpYzPoow=="], - - "utf-8-validate": ["utf-8-validate@5.0.10", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ=="], - - "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], - - "uuid": ["uuid@11.0.3", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg=="], - - "viem": ["viem@2.29.4", "", { "dependencies": { "@noble/curves": "1.8.2", "@noble/hashes": "1.7.2", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-Dhyae+w1LKKpYVXypGjBnZ3WU5EHl/Uip5RtVwVRYSVxD5VvHzqKzIfbFU1KP4vnnh3++ZNgLjBY/kVT/tPrrg=="], - - "vite": ["vite@6.3.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="], - - "vite-node": ["vite-node@3.1.3", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.0", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-uHV4plJ2IxCl4u1up1FQRrqclylKAogbtBfOTwcuJ28xFi+89PZ57BRh+naIRvH70HPwxy5QHYzg1OrEaC7AbA=="], - - "vitest": ["vitest@3.1.3", "", { "dependencies": { "@vitest/expect": "3.1.3", "@vitest/mocker": "3.1.3", "@vitest/pretty-format": "^3.1.3", "@vitest/runner": "3.1.3", "@vitest/snapshot": "3.1.3", "@vitest/spy": "3.1.3", "@vitest/utils": "3.1.3", "chai": "^5.2.0", "debug": "^4.4.0", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.13", "tinypool": "^1.0.2", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0", "vite-node": "3.1.3", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.1.3", "@vitest/ui": "3.1.3", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-188iM4hAHQ0km23TN/adso1q5hhwKqUpv+Sd6p5sOuh6FhQnRNW3IsiIpvxqahtBabsJ2SLZgmGSpcYK4wQYJw=="], - - "web-streams-polyfill": ["web-streams-polyfill@4.0.0-beta.3", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="], - - "webidl-conversions": ["webidl-conversions@4.0.2", "", {}, "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg=="], - - "whatwg-url": ["whatwg-url@7.1.0", "", { "dependencies": { "lodash.sortby": "^4.7.0", "tr46": "^1.0.1", "webidl-conversions": "^4.0.2" } }, "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg=="], - - "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], - - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - - "wordwrap": ["wordwrap@1.0.0", "", {}, "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q=="], - - "wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="], - - "wrap-ansi-cjs": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], - - "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], - - "ws": ["ws@8.18.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w=="], - - "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], - - "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], - - "yaml": ["yaml@2.8.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ=="], - - "yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], - - "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], - - "zod": ["zod@3.24.4", "", {}, "sha512-OdqJE9UDRPwWsrHjLN2F8bPxvwJBK22EHLWtanu0LSYr5YqzsaaW3RMgmjwr8Rypg5k+meEJdSPXJZXE/yqOMg=="], - - "zod-to-json-schema": ["zod-to-json-schema@3.24.5", "", { "peerDependencies": { "zod": "^3.24.1" } }, "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g=="], - - "@langchain/core/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], - - "@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.33.0", "", {}, "sha512-TIpZvE8fiEILFfTlfPnltpBaD3d9/+uQHVCyC3vfdh6WfCXKhNFzoP5RyDDIndfvZC5GrA4pyEDNyjPloJud+w=="], - - "@scure/bip32/@noble/curves": ["@noble/curves@1.8.2", "", { "dependencies": { "@noble/hashes": "1.7.2" } }, "sha512-vnI7V6lFNe0tLAuJMu+2sX+FcL14TaCWy1qiczg1VwRmPrpQCdq5ESXQMqUc2tluRNf6irBXrWbl1mGN8uaU/g=="], - - "@scure/bip32/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], - - "@scure/bip39/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], - - "@solana/errors/chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="], - - "@solana/errors/commander": ["commander@13.1.0", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="], - - "asn1.js/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "browserify-sign/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], - - "chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - - "cliui/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - - "cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], - - "create-ecdh/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "diffie-hellman/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "elliptic/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "handlebars/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], - - "jayson/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="], - - "jayson/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], - - "jayson/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], - - "jayson/ws": ["ws@7.5.10", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ=="], - - "langchain/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], - - "langsmith/@types/uuid": ["@types/uuid@10.0.0", "", {}, "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="], - - "langsmith/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="], - - "miller-rabin/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], - - "openai/@types/node": ["@types/node@18.19.100", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-ojmMP8SZBKprc3qGrGk8Ujpo80AXkrP7G2tOT4VWr5jlr5DHjsJF+emXJz+Wm0glmy4Js62oKMdZZ6B9Y+tEcA=="], - - "p-queue/eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="], - - "public-encrypt/bn.js": ["bn.js@4.12.2", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="], - - "rpc-websockets/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], - - "rpc-websockets/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], - - "string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "string-width-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "strip-ansi-cjs/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "sucrase/glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="], - - "viem/@noble/curves": ["@noble/curves@1.8.2", "", { "dependencies": { "@noble/hashes": "1.7.2" } }, "sha512-vnI7V6lFNe0tLAuJMu+2sX+FcL14TaCWy1qiczg1VwRmPrpQCdq5ESXQMqUc2tluRNf6irBXrWbl1mGN8uaU/g=="], - - "viem/@noble/hashes": ["@noble/hashes@1.7.2", "", {}, "sha512-biZ0NUSxyjLLqo6KxEJ1b+C2NAx0wtDoFvCaXHGgUkeHzf3Xc1xKumFKREuT7f7DARNZ/slvYUwFG6B0f2b6hQ=="], - - "wrap-ansi/ansi-styles": ["ansi-styles@6.2.1", "", {}, "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug=="], - - "wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - - "wrap-ansi-cjs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - - "wrap-ansi-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - - "browserify-sign/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], - - "browserify-sign/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], - - "cliui/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - - "node-fetch/whatwg-url/tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], - - "node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], - - "openai/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], - - "string-width-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "sucrase/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], - - "sucrase/glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], - - "sucrase/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - - "wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "wrap-ansi-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "sucrase/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - - "yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - } -} From 2e63cb0e0b6ddb0fd25def74d6f14fb7314defad Mon Sep 17 00:00:00 2001 From: cjft Date: Fri, 30 May 2025 17:12:08 -0600 Subject: [PATCH 36/39] chore: update version to 1.0.0 and @elizaos/core to ^1.0.0 --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 1a06923..1c6c89e 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0-beta.81", + "version": "1.0.0", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "dependencies": { - "@elizaos/core": "^1.0.0-beta.76", + "@elizaos/core": "^1.0.0", "@phala/dstack-sdk": "0.1.11", "@solana/web3.js": "1.98.2", "viem": "2.29.4" From 79794af917424c3555b66e6345ddd8028786d864 Mon Sep 17 00:00:00 2001 From: Agent Config Scanner Date: Sun, 8 Jun 2025 10:28:55 -0600 Subject: [PATCH 37/39] chore: update agentConfig and bump version --- package.json | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 1c6c89e..792a767 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.0", + "version": "1.0.1", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", @@ -32,14 +32,18 @@ "agentConfig": { "pluginType": "elizaos:plugin:1.0.0", "pluginParameters": { - "TEE_VENDOR": { - "type": "string" - }, "TEE_MODE": { - "type": "string" + "type": "string", + "description": "Determines the Trusted Execution Environment operation mode (LOCAL, DOCKER, PRODUCTION) which controls how the provider connects to the TEE simulator or production environment.", + "required": true, + "sensitive": false }, "WALLET_SECRET_SALT": { - "type": "string" + "type": "string", + "description": "Secret salt used as input to deterministically derive Solana and EVM keypairs inside the TEE.", + "required": true, + "default": "secret_salt", + "sensitive": true } } }, From 6744a7a3d5b64633c89c4bb63e927e43e4a5e23f Mon Sep 17 00:00:00 2001 From: Agent Config Scanner Date: Sun, 8 Jun 2025 10:55:44 -0600 Subject: [PATCH 38/39] chore: update agentConfig and bump version --- package.json | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 792a767..ba04fd1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.1", + "version": "1.0.2", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", @@ -34,13 +34,20 @@ "pluginParameters": { "TEE_MODE": { "type": "string", - "description": "Determines the Trusted Execution Environment operation mode (LOCAL, DOCKER, PRODUCTION) which controls how the provider connects to the TEE simulator or production environment.", + "description": "Determines the Trusted Execution Environment operation mode (LOCAL, DOCKER, PRODUCTION) and is referenced in error handling to validate provided modes.", "required": true, "sensitive": false }, + "TEE_VENDOR": { + "type": "string", + "description": "Specifies which Trusted Execution Environment vendor to initialize (defaults to PHALA).", + "required": false, + "default": "PHALA", + "sensitive": false + }, "WALLET_SECRET_SALT": { "type": "string", - "description": "Secret salt used as input to deterministically derive Solana and EVM keypairs inside the TEE.", + "description": "Secret salt used to deterministically derive Solana and EVM keypairs inside the TEE.", "required": true, "default": "secret_salt", "sensitive": true From ba16e862f7868598e1aa78a4ed7cf14f1b4271f6 Mon Sep 17 00:00:00 2001 From: hashwarlock Date: Mon, 27 Oct 2025 00:19:58 -0500 Subject: [PATCH 39/39] fix: update dstack to latest version --- package.json | 4 +- src/__tests__/deriveKey.test.ts | 34 +++++++-------- src/__tests__/remoteAttestation.test.ts | 30 ++++++------- src/__tests__/timeout.test.ts | 50 +++++++++++----------- src/providers/base.ts | 7 ++- src/providers/deriveKeyProvider.ts | 22 +++++----- src/providers/remoteAttestationProvider.ts | 17 +++----- src/service.ts | 4 +- 8 files changed, 82 insertions(+), 86 deletions(-) diff --git a/package.json b/package.json index ba04fd1..4c951e9 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "@elizaos/plugin-tee", - "version": "1.0.2", + "version": "1.0.3", "main": "dist/index.js", "type": "module", "types": "dist/index.d.ts", "dependencies": { "@elizaos/core": "^1.0.0", - "@phala/dstack-sdk": "0.1.11", + "@phala/dstack-sdk": "0.5.7", "@solana/web3.js": "1.98.2", "viem": "2.29.4" }, diff --git a/src/__tests__/deriveKey.test.ts b/src/__tests__/deriveKey.test.ts index 7b18bbf..2cdbb95 100644 --- a/src/__tests__/deriveKey.test.ts +++ b/src/__tests__/deriveKey.test.ts @@ -1,15 +1,15 @@ import { TEEMode } from "@elizaos/core"; -import { TappdClient } from "@phala/dstack-sdk"; +import { DstackClient } from "@phala/dstack-sdk"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { PhalaDeriveKeyProvider } from "../providers/deriveKeyProvider"; // Mock dependencies vi.mock("@phala/dstack-sdk", () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - deriveKey: vi.fn().mockResolvedValue({ + DstackClient: vi.fn().mockImplementation(() => ({ + getKey: vi.fn().mockResolvedValue({ asUint8Array: () => new Uint8Array([1, 2, 3, 4, 5]), }), - tdxQuote: vi.fn().mockResolvedValue({ + getQuote: vi.fn().mockResolvedValue({ quote: "mock-quote-data", replayRtmrs: () => ["rtmr0", "rtmr1", "rtmr2", "rtmr3"], }), @@ -41,19 +41,19 @@ describe("DeriveKeyProvider", () => { describe("constructor", () => { it("should initialize with LOCAL mode", () => { const _provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith("http://localhost:8090"); + expect(DstackClient).toHaveBeenCalledWith("http://localhost:8090"); }); it("should initialize with DOCKER mode", () => { const _provider = new PhalaDeriveKeyProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith( + expect(DstackClient).toHaveBeenCalledWith( "http://host.docker.internal:8090" ); }); it("should initialize with PRODUCTION mode", () => { const _provider = new PhalaDeriveKeyProvider(TEEMode.PRODUCTION); - expect(TappdClient).toHaveBeenCalledWith(); + expect(DstackClient).toHaveBeenCalledWith(); }); it("should throw error for invalid mode", () => { @@ -75,18 +75,18 @@ describe("DeriveKeyProvider", () => { const subject = "test-subject"; const result = await _provider.rawDeriveKey(path, subject); - const client = vi.mocked(TappdClient).mock.results[0].value; - expect(client.deriveKey).toHaveBeenCalledWith(path, subject); - expect(result.asUint8Array()).toEqual(new Uint8Array([1, 2, 3, 4, 5])); + const client = vi.mocked(DstackClient).mock.results[0].value; + expect(client.getKey).toHaveBeenCalledWith(path, subject); + expect(result.key).toEqual(new Uint8Array([1, 2, 3, 4, 5])); }); it("should handle errors during raw key derivation", async () => { const mockError = new Error("Key derivation failed"); - vi.mocked(TappdClient).mockImplementationOnce(() => { - const instance = new TappdClient(); - instance.deriveKey = vi.fn().mockRejectedValueOnce(mockError); - instance.tdxQuote = vi.fn(); - instance.deriveKey = vi.fn(); + vi.mocked(DstackClient).mockImplementationOnce(() => { + const instance = new DstackClient(); + instance.getKey = vi.fn().mockRejectedValueOnce(mockError); + instance.getQuote = vi.fn(); + instance.getKey = vi.fn(); return instance; }); @@ -113,8 +113,8 @@ describe("DeriveKeyProvider", () => { "test-agent-id" ); - const client = vi.mocked(TappdClient).mock.results[0].value; - expect(client.deriveKey).toHaveBeenCalledWith(path, subject); + const client = vi.mocked(DstackClient).mock.results[0].value; + expect(client.getKey).toHaveBeenCalledWith(path, subject); expect(result.keypair.publicKey.toBase58()).toEqual( "mock-solana-public-key" ); diff --git a/src/__tests__/remoteAttestation.test.ts b/src/__tests__/remoteAttestation.test.ts index 509e051..fade125 100644 --- a/src/__tests__/remoteAttestation.test.ts +++ b/src/__tests__/remoteAttestation.test.ts @@ -1,16 +1,16 @@ import { TEEMode } from "@elizaos/core"; -import { TappdClient } from "@phala/dstack-sdk"; +import { DstackClient } from "@phala/dstack-sdk"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { PhalaRemoteAttestationProvider } from "../providers/remoteAttestationProvider"; -// Mock TappdClient +// Mock DstackClient vi.mock("@phala/dstack-sdk", () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - tdxQuote: vi.fn().mockResolvedValue({ + DstackClient: vi.fn().mockImplementation(() => ({ + getQuote: vi.fn().mockResolvedValue({ quote: "mock-quote-data", replayRtmrs: () => ["rtmr0", "rtmr1", "rtmr2", "rtmr3"], }), - deriveKey: vi.fn(), + getKey: vi.fn(), endpoint: "http://localhost:8090", info: vi.fn().mockResolvedValue({}), })), @@ -24,19 +24,19 @@ describe("PhalaRemoteAttestationProvider", () => { describe("constructor", () => { it("should initialize with LOCAL mode", () => { const _provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); - expect(TappdClient).toHaveBeenCalledWith("http://localhost:8090"); + expect(DstackClient).toHaveBeenCalledWith("http://localhost:8090"); }); it("should initialize with DOCKER mode", () => { const _provider = new PhalaRemoteAttestationProvider(TEEMode.DOCKER); - expect(TappdClient).toHaveBeenCalledWith( + expect(DstackClient).toHaveBeenCalledWith( "http://host.docker.internal:8090" ); }); it("should initialize with PRODUCTION mode", () => { const _provider = new PhalaRemoteAttestationProvider(TEEMode.PRODUCTION); - expect(TappdClient).toHaveBeenCalledWith(); + expect(DstackClient).toHaveBeenCalledWith(); }); it("should throw error for invalid mode", () => { @@ -66,12 +66,12 @@ describe("PhalaRemoteAttestationProvider", () => { it("should handle errors during attestation generation", async () => { const mockError = new Error("TDX Quote generation failed"); const mockTdxQuote = vi.fn().mockRejectedValue(mockError); - vi.mocked(TappdClient).mockImplementationOnce( + vi.mocked(DstackClient).mockImplementationOnce( () => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: mockTdxQuote, + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); @@ -83,10 +83,10 @@ describe("PhalaRemoteAttestationProvider", () => { it("should pass hash algorithm to tdxQuote when provided", async () => { const reportData = "test-report-data"; const hashAlgorithm = "raw"; - await provider.generateAttestation(reportData, hashAlgorithm); + await provider.generateAttestation(reportData); - const client = vi.mocked(TappdClient).mock.results[0].value; - expect(client.tdxQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); + const client = vi.mocked(DstackClient).mock.results[0].value; + expect(client.getQuote).toHaveBeenCalledWith(reportData, hashAlgorithm); }); }); }); diff --git a/src/__tests__/timeout.test.ts b/src/__tests__/timeout.test.ts index 136232a..a837da0 100644 --- a/src/__tests__/timeout.test.ts +++ b/src/__tests__/timeout.test.ts @@ -1,14 +1,14 @@ import { TEEMode } from "@elizaos/core"; -import { TappdClient } from "@phala/dstack-sdk"; +import { DstackClient } from "@phala/dstack-sdk"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { PhalaDeriveKeyProvider } from "../providers/deriveKeyProvider"; import { PhalaRemoteAttestationProvider } from "../providers/remoteAttestationProvider"; -// Mock TappdClient +// Mock DstackClient vi.mock("@phala/dstack-sdk", () => ({ - TappdClient: vi.fn().mockImplementation(() => ({ - tdxQuote: vi.fn(), - deriveKey: vi.fn(), + DstackClient: vi.fn().mockImplementation(() => ({ + getQuote: vi.fn(), + getKey: vi.fn(), endpoint: "http://localhost:8090", // Add this info: vi.fn().mockResolvedValue({}), // Add this })), @@ -25,12 +25,12 @@ describe("TEE Provider Timeout Tests", () => { .fn() .mockRejectedValueOnce(new Error("Request timed out")); - vi.mocked(TappdClient).mockImplementation( + vi.mocked(DstackClient).mockImplementation( () => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: mockTdxQuote, + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); @@ -48,12 +48,12 @@ describe("TEE Provider Timeout Tests", () => { .fn() .mockRejectedValueOnce(new Error("Network error")); - vi.mocked(TappdClient).mockImplementation( + vi.mocked(DstackClient).mockImplementation( () => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: mockTdxQuote, + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); @@ -72,12 +72,12 @@ describe("TEE Provider Timeout Tests", () => { const mockTdxQuote = vi.fn().mockResolvedValueOnce(mockQuote); - vi.mocked(TappdClient).mockImplementation( + vi.mocked(DstackClient).mockImplementation( () => ({ - tdxQuote: mockTdxQuote, - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: mockTdxQuote, + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaRemoteAttestationProvider(TEEMode.LOCAL); @@ -97,12 +97,12 @@ describe("TEE Provider Timeout Tests", () => { .fn() .mockRejectedValueOnce(new Error("Request timed out")); - vi.mocked(TappdClient).mockImplementation( + vi.mocked(DstackClient).mockImplementation( () => ({ - tdxQuote: vi.fn(), - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: vi.fn(), + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); @@ -119,12 +119,12 @@ describe("TEE Provider Timeout Tests", () => { .fn() .mockRejectedValueOnce(new Error("Request timed out")); - vi.mocked(TappdClient).mockImplementation( + vi.mocked(DstackClient).mockImplementation( () => ({ - tdxQuote: vi.fn(), - deriveKey: vi.fn(), - }) as unknown as TappdClient + getQuote: vi.fn(), + getKey: vi.fn(), + }) as unknown as DstackClient ); const provider = new PhalaDeriveKeyProvider(TEEMode.LOCAL); diff --git a/src/providers/base.ts b/src/providers/base.ts index 62d497d..90beddc 100644 --- a/src/providers/base.ts +++ b/src/providers/base.ts @@ -7,15 +7,15 @@ import type { TdxQuoteHashAlgorithms } from "@phala/dstack-sdk"; * @example * ```ts * class MyDeriveKeyProvider extends DeriveKeyProvider { - * private client: TappdClient; + * private client: DstackClient; * * constructor(endpoint: string) { * super(); - * this.client = new TappdClient(); + * this.client = new DstackClient(); * } * * async rawDeriveKey(path: string, subject: string): Promise { - * return this.client.deriveKey(path, subject); + * return this.client.getKey(path, subject); * } * } * ``` @@ -31,6 +31,5 @@ export abstract class DeriveKeyProvider {} export abstract class RemoteAttestationProvider { abstract generateAttestation( reportData: string, - hashAlgorithm?: TdxQuoteHashAlgorithms ): Promise; } diff --git a/src/providers/deriveKeyProvider.ts b/src/providers/deriveKeyProvider.ts index 6bcc62c..927e9b2 100644 --- a/src/providers/deriveKeyProvider.ts +++ b/src/providers/deriveKeyProvider.ts @@ -9,7 +9,7 @@ import { type RemoteAttestationQuote, TEEMode, } from "@elizaos/core"; -import { type DeriveKeyResponse, TappdClient } from "@phala/dstack-sdk"; +import { type GetKeyResponse, DstackClient } from "@phala/dstack-sdk"; import { DeriveKeyProvider } from "./base"; import { PhalaRemoteAttestationProvider as RemoteAttestationProvider } from "./remoteAttestationProvider"; import { type PrivateKeyAccount, privateKeyToAccount } from 'viem/accounts'; @@ -29,7 +29,7 @@ import crypto from 'node:crypto'; * Extends the DeriveKeyProvider class. */ class PhalaDeriveKeyProvider extends DeriveKeyProvider { - private client: TappdClient; + private client: DstackClient; private raProvider: RemoteAttestationProvider; constructor(teeMode?: string) { @@ -58,7 +58,7 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { ); } - this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + this.client = endpoint ? new DstackClient(endpoint) : new DstackClient(); this.raProvider = new RemoteAttestationProvider(teeMode); } @@ -88,14 +88,14 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { async rawDeriveKey( path: string, subject: string - ): Promise { + ): Promise { try { if (!path || !subject) { logger.error("Path and Subject are required for key derivation"); } logger.log("Deriving Raw Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); + const derivedKey = await this.client.getKey(path, subject); logger.log("Raw Key Derived Successfully!"); return derivedKey; @@ -118,13 +118,13 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { agentId: string ): Promise<{ keypair: Keypair; attestation: RemoteAttestationQuote }> { try { - if (!path || !subject) { - logger.error("Path and Subject are required for key derivation"); + if (!path) { + logger.error("Path is required for key derivation"); } logger.log("Deriving Ed25519 Key in TEE..."); - const derivedKey = await this.client.deriveKey(path, subject); - const uint8ArrayDerivedKey = derivedKey.asUint8Array(); + const derivedKey = await this.client.getKey(path, subject); + const uint8ArrayDerivedKey = derivedKey.key; const hash = crypto.createHash('sha256'); hash.update(uint8ArrayDerivedKey); const seed = hash.digest(); @@ -166,11 +166,11 @@ class PhalaDeriveKeyProvider extends DeriveKeyProvider { } logger.log("Deriving ECDSA Key in TEE..."); - const deriveKeyResponse: DeriveKeyResponse = await this.client.deriveKey( + const deriveKeyResponse: GetKeyResponse = await this.client.getKey( path, subject ); - const hex = keccak256(deriveKeyResponse.asUint8Array()); + const hex = keccak256(deriveKeyResponse.key); const keypair: PrivateKeyAccount = privateKeyToAccount(hex) as unknown as PrivateKeyAccount; diff --git a/src/providers/remoteAttestationProvider.ts b/src/providers/remoteAttestationProvider.ts index 316b8d0..62aa0db 100644 --- a/src/providers/remoteAttestationProvider.ts +++ b/src/providers/remoteAttestationProvider.ts @@ -10,9 +10,8 @@ import { TEEMode, } from "@elizaos/core"; import { - TappdClient, - type TdxQuoteHashAlgorithms, - type TdxQuoteResponse, + DstackClient, + type GetQuoteResponse, } from "@phala/dstack-sdk"; import { RemoteAttestationProvider } from "./base"; @@ -42,7 +41,7 @@ interface ProviderResult { * @extends RemoteAttestationProvider */ class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { - private client: TappdClient; + private client: DstackClient; constructor(teeMode?: string) { super(); @@ -70,25 +69,23 @@ class PhalaRemoteAttestationProvider extends RemoteAttestationProvider { ); } - this.client = endpoint ? new TappdClient(endpoint) : new TappdClient(); + this.client = endpoint ? new DstackClient(endpoint) : new DstackClient(); } async generateAttestation( reportData: string, - hashAlgorithm?: TdxQuoteHashAlgorithms ): Promise { try { logger.log("Generating attestation for: ", reportData); - const tdxQuote: TdxQuoteResponse = await this.client.tdxQuote( + const getQuote: GetQuoteResponse = await this.client.getQuote( reportData, - hashAlgorithm ); - const rtmrs = tdxQuote.replayRtmrs(); + const rtmrs = getQuote.replayRtmrs(); logger.log( `rtmr0: ${rtmrs[0]}\nrtmr1: ${rtmrs[1]}\nrtmr2: ${rtmrs[2]}\nrtmr3: ${rtmrs[3]}f` ); const quote: RemoteAttestationQuote = { - quote: tdxQuote.quote, + quote: getQuote.quote, timestamp: Date.now(), }; logger.log("Remote attestation quote: ", quote); diff --git a/src/service.ts b/src/service.ts index 0a93fbc..fe107ad 100644 --- a/src/service.ts +++ b/src/service.ts @@ -3,7 +3,7 @@ import { PrivateKeyAccount } from 'viem'; import { Keypair } from '@solana/web3.js'; import { type RemoteAttestationQuote } from '@elizaos/core'; import { PhalaDeriveKeyProvider } from './providers/deriveKeyProvider'; -import { DeriveKeyResponse } from '@phala/dstack-sdk'; +import { GetKeyResponse } from '@phala/dstack-sdk'; interface TEEServiceConfig { teeMode?: string; @@ -61,7 +61,7 @@ export class TEEService extends Service { async rawDeriveKey( path: string, subject: string - ): Promise { + ): Promise { logger.log('TEE Service: Deriving Raw Key'); return await this.provider.rawDeriveKey(path, subject); }